/* Minification failed. Returning unminified contents.
(7623,95-96): run-time error JS1195: Expected expression: ?
(16430,91-92): run-time error JS1100: Expected ',': =
(16430,95-96): run-time error JS1002: Syntax error: ,
(16430,110-111): run-time error JS1100: Expected ',': =
(16430,115-116): run-time error JS1002: Syntax error: ,
(16430,126-127): run-time error JS1100: Expected ',': =
 */
(function () {
    'use strict';

    // indexOf is missing on arrays in IE, add it
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (el) {
            var len = this.length >>> 0;

            var from = Number(arguments[1]) || 0;
            from = (from < 0) ? Math.ceil(from) : Math.floor(from);
            if (from < 0) { from += len; }
            for (; from < len; from++) {
                if (from in this && this[from] === el) return from;
            }
            return -1;
        };
    }


    // startsWith is missing in IE, add it
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (str, startPos) {
            if (!startPos) { startPos = 0; }
            return this.indexOf(str, startPos) === startPos;
        };
	}

	// String.includes is missing in IE, add it
	if (!String.prototype.includes) {
		String.prototype.includes = function (search, start) {
			'use strict';
			if (typeof start !== 'number') {
				start = 0;
			}

			if (start + search.length > this.length) {
				return false;
			} else {
				return this.indexOf(search, start) !== -1;
			}
		};
	}

    // start angular stuff

	angular
		.module('app', [
			// Angular modules
			'ngSanitize',
			'ngAnimate',
			'ngCookies',
			'ngTouch',
			'ngResource',
			'ngAria',

			// 3rd Party Modules
			'ui.bootstrap',
			'ui.bootstrap.buttons',
			'ui.bootstrap.dropdown',
			'ui.bootstrap.popover',
			'ui.bootstrap.pagination',
			'ui.bootstrap.datepicker',
			'ui.bootstrap.typeahead',
			'ui.router',
			'ui.uploader',
			'ui.event',
			'ui.highlight',
			'nemLogging',
			'ui-leaflet',
			'ui.grid',
			'ui.grid.autoResize',
			'ui.grid.expandable',
			'ui.grid.grouping',
			'ui.scrollpoint',
			'ui.validate',
			'ui.tour',
			'toastr',
			//'ui.grid.cellNav',
			'smart-table',
			'ngIdle',
			'jlareau.bowser',
			'angular-storage',
			// 'ngScrollbar'

			// custom modules
			'app.route-config'
		])
		.constant('_', window._)
		.constant('APP_ROLES', {
			"Public": "PUBLIC",
			"StructureAnalyst": "STRUCTURE_ANALYST_RW",
			"UserAdmin": "ADMIN_USERACCOUNTS_RW",
			"DataAnalyst": "DATA_ANALYST_RW",
			"DataRefreshAdmin": "ADMIN_DATA_REFRESH_RW",
			"MappingAnalyst": "MAPPING_ANALYST_RW",
			"CaseWorker": "CASE_WORKER_R"
		})
		.constant('MENU_ROLES', {
			"CaseWork": "0",
			"StructureMaintenance": "1"
		})
		.constant('THRIFT_WEIGHT_RULE_IDS', {
			"Default": 0,
			"BOG": 1,
			"DOJ": 2
		})
		.constant('FEATURE_TOGGLES', {
			"ChangePacketIntegration": true
		})
		.constant('COOKIE_KEYS', {
			"LastLoginInfo": 'seenLoginDateNote'
		})
        .config(["IdleProvider", "KeepaliveProvider", function (IdleProvider, KeepaliveProvider) {
            IdleProvider.idle(3600); // 3600s = 60 minutes of inactivity leads to session expiration
            IdleProvider.timeout(30); // in last 30 seconds, show warning and timer countdown
            //KeepaliveProvider.interval(23); // every 30s, hit server to keep session alive
            KeepaliveProvider.interval(120); // set interval to once every 2 minutes
            KeepaliveProvider.http("api/util/keep-alive");
            // NOTE: Idle.watch() is called when disclaimer is accepted (DisclaimerService) or advanced user logs in (LoginController)
        }])
        //.config(['toastrConfig', function (toastrConfig) {
        //    angular.extend(toastrConfig, {
        //        preventDuplicates: true
        //    });
        //}])
        // ********** ********** ********** ******************************************* ********** ********** **********
        // ********** ********** ********** ******************************************* ********** ********** **********
        // ********** ********** ********** NOTE: ROUTES defined in app.route-config.js ********** ********** **********
        // ********** ********** ********** ******************************************* ********** ********** **********
        // ********** ********** ********** ******************************************* ********** ********** **********
		.run(['$http', 'config', '$state', '$rootScope', '$log', '$uibModal', '$window', '$location', 'AuthService', 'UserData', 'Dialogger', 'APP_ROLES', 'Idle', 'DisclaimerService', 'FEATURE_TOGGLES', 'COOKIE_KEYS', '$cookies',
			function ($http, config, $state, $rootScope, $log, $uibModal, $window, $location, Auth, UserData, Dialogger, APP_ROLES, Idle, Disclaimer, FEATURE_TOGGLES, COOKIE_KEYS, $cookies) {
                // Add anti-forgery token
                $http.defaults.headers.common["X-XSRF-Token"] = config.antiForgeryToken;
                $rootScope._ = window._;
                $rootScope.ROLES = APP_ROLES;
				$rootScope.FeatureToggles = FEATURE_TOGGLES;
                $rootScope.isDev = $location.host().substr(0, 9) == "localhost";

                $rootScope.navbarCollapsed = true;
                $rootScope.sidenavCollapsed = false;

                //if (!window.WebTrends || !window._tag) {
                //    $log.warn("NO WebTrends!");
                //}

                Auth.check(); // Get in a logged-in state, if user actually is logged in

                if (Disclaimer.isAccepted() && !Idle.running())
                    Idle.watch();

                $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
                    var value = Idle.getIdle();
                    $window.scrollTo(0, 0);
                    if (toState.data.isAdvanced === true)
                    {
                        if (value != 3600)
                            Idle.setIdle(3600);
                    }
                    if (toState.data.isAdvanced === false) {
                        if (value != 1800)
                            Idle.setIdle(1800);
                    }
                    // Is authentication required?
					if (toState.data.isAdvanced === true) {
						//if (!Auth.isLoggedInAsync()) {
						if (!Auth.isLoggedIn(config.authMethod == "Forms")) {
                            e.preventDefault();
                            $rootScope.afterLoginState = { state: toState, params: toParams };
                            $state.go("root.login");

                        } else if (!Auth.isAuthorized()) { // does logged in user have minimal role(s) necessary for access?
                            e.preventDefault();
                            $state.go("root.not-allowed");
                        }
                    }

                    // Is disclaimer needed and accepted?
                    if (toState.data.requiresDisclaimer === true && !toState.data.showDisclaimerOnPageComplete && !Disclaimer.isAccepted()) {
                        e.preventDefault();
                        $uibModal.open({
                            animation: true,
                            size: 'lg',
                            keyboard: false,
                            backdrop: false,
                            templateUrl: 'AppJs/common/tpls/disclaimer.html'
                        }).result.then(function (accepted) {
                            if (accepted === true) {
                                Disclaimer.accept();

                                $state.go(toState, toParams);

                            }
                        }, function () {
                            //on Cancel, ensure user ends up on a real page
                            if ((fromState.data && fromState.data.requiresDisclaimer) || fromState.abstract) {
                                window.location = "https://www.stlouisfed.org/";
                            }
                        });
                    }

                    // Are we logging out?
                    if (toState.name == "root.logout") {
                        e.preventDefault();
                        Auth.logout()
							.then(function (isOk) {	
								$cookies.remove(COOKIE_KEYS.LastLoginInfo);
                                if (fromState.data.isAdvanced) {
                                    $state.go("root.login", { loggedOut: true });
                                    // $window.location.reload();  // reload the entire page so that we totally refresh the Angular app & clean out everything from previous login session
                                }
                                else
                                    $state.go("root.index");
                            });
                    }

                    // Going from non-Advanced to Advanced, with saved Markets or Buyer/Targets
                    if ((fromState.data && !fromState.data.isAdvanced) && (toState.data && toState.data.isAdvanced === true)
                        && (UserData.buyerInstitutions.any() || UserData.targetInstitutions.any())) {

                        var instList = _.concat([], UserData.buyerInstitutions.get(), UserData.targetInstitutions.get());
                        instList = _.differenceBy(instList, UserData.institutions.get(), 'rssdId');

                        if (instList.length > 0) {

                            Dialogger
                                .confirm("You have saved buyer and/or target institutions. Do you want to make them available " +
                                    "for reference in the Advanced area?", "Copy Institutions Forward?", true)
                                .then(function (copyForward) {
                                    if (copyForward)
                                        _(instList).forEach(UserData.institutions.save);
                                });
                        }
                    }

                    // Are we moving back to search page after looking at search results list?
                    if ((toState.name == "root.institutions.search" && fromState.name == "root.institutions.list")
                        || (toState.name == "root.markets.search" && fromState.name == "root.markets.list")) {
                        $rootScope.keepSearchCriteria = true;
                    } else
                        $rootScope.keepSearchCriteria = false;

                });

                $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {

                    if (error.status == 401) {
                        //console.log("401 detected. Redirecting...");

                        var loginUrl = "/login?returnUrl=" + $state.href(toState, toParams);
                        $window.location.href = loginUrl;
                    }
                });

                $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                    $rootScope.lastState = $rootScope.currentState || "";
                    $rootScope.currentState = toState.name;
                    $rootScope.title = toState.data.title;
                    $rootScope.isAdvanced = toState.data.isAdvanced;
                    $rootScope.showPrintButton = toState.data.showPrintButton;
                    $rootScope.hideBreadCrumb = toState.data.hideBreadCrumb;

                    if (toState.data.requiresDisclaimer === true && toState.data.showDisclaimerOnPageComplete === true && !Disclaimer.isAccepted()) {
                        $uibModal.open({
                            animation: true,
                            size: 'lg',
                            keyboard: false,
                            backdrop: false,
                            templateUrl: 'AppJs/common/tpls/disclaimer.html'
                        }).result.then(function (accepted) {
                            if (accepted === true) {
                                Disclaimer.accept();

                                $state.go(toState, toParams);
                                $window.location.reload();

                            }
                        }, function () {
                            //on Cancel, ensure user ends up on a real page
                            if ((fromState.data && fromState.data.requiresDisclaimer) || fromState.abstract)
                                window.location = "https://www.stlouisfed.org/";
                        });
                    }

                    //WebTrends
                    //if (window._tag) {
                    //    //window._tag.dcsCustom = function () {
                    //    // Add custom parameters here.
                    //    // window._tag.DCSext.param_name=param_value;
                    //    //}
                    //    window._tag.dcsCollect();
                    //}

                    //if (fromState.name != toState.name)
                    //    document.body.scrollTop = document.documentElement.scrollTop = 0;
                });

                $rootScope.$on('Keepalive', function () {
                    Disclaimer.update();
                });

                $rootScope.$on('IdleTimeout', function () {
                    Disclaimer.clear();
                });


                // Back to Top ///////
                $(window).scroll(function () {
                    if ($(this).scrollTop() > 50) {
                        $('#back-to-top').fadeIn();
                    } else {
                        $('#back-to-top').fadeOut();
                    }
                });
                // scroll body to 0px on click
                $('#back-to-top').click(function () {
                    //$('#back-to-top').tooltip('hide');
                    $('body,html').animate({ scrollTop: 0 }, 800);
                    return false;
                });

                //$('#back-to-top').tooltip('show');

            }])
        .filter('noUnderscore', function () { return function (str) { return str.replace(/_/g, ' ') } })
        .filter('digits', function () {
            return function (input, width, leadingChar) {
                leadingChar = leadingChar || '0';
                input = input + '';
                return input.length >= width ? input : new Array(width - input.length + 1).join(leadingChar) + input;
            }
        })
        .directive('focusWhenVarTrue', focusWhenVarTrue);

    focusWhenVarTrue.$inject = ['$timeout', '$parse'];

    function focusWhenVarTrue($timeout, $parse) {
        return {
            restrict: "A",
            link: function (scope, domElement, attrs) {
                var model = $parse(attrs.focusWhenVarTrue);
                scope.$watch(model, function (val) {
                    if (val === true) {
                        var inputElement = false;
                        if ($(domElement[0]).is(':input')) {
                            inputElement = domElement[0];
                        }
                        else {
                            var childInputs = $(domElement[0]).find(':input');
                            if (childInputs.length > 0) {
                                inputElement = childInputs[0];
                            }
                        }
                        if (inputElement != false) {
                            $timeout(function () { inputElement.focus(); }, 100)
                        }
                    }
                });
            }
        }

        };
})();

;
(function () {
    'use strict';

    angular
      .module('app')
      .factory('AnalysisService', AnalysisService);

    AnalysisService.$inject = ['$http', '$log'];

    function AnalysisService($http, $log) {
        var service = {
            getCommonMarkets: getCommonMarkets
        };

        return service;
        ////////////////

		function getCommonMarkets(buyer, targets, branches) {
            return $http.get('/api/analysis/common-markets', { params: { buyer: buyer, targets: targets, branches: branches } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning common markets data", result);
                });
        }
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('DataSetService', DataSetService);

    DataSetService.$inject = ['$resource'];

    function DataSetService($resource) {
        return $resource("/api/datasets/:id", { id: '@id' });
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('DemoController', DemoController);

    DemoController.$inject = ['$scope', '$state', 'Dialogger'];

    function DemoController($scope, $state, Dialogger) {
        console.log("DemoController-->state.name = [" + $state.current.name + "]");
        $scope.state = $state.current.name;

        // DatePicker demo
        $scope.theDate;
        $scope.datePickerOptions = {
            minDate: new Date(),
            showWeeks: true
        };

        // Dialogger demo
        angular.extend($scope, {
            showAlert: function () { Dialogger.alert("This is an alert message!"); },
            showLongAlert: function () { Dialogger.alert("This is an alert message! This is an alert message! This is an alert message! This is an alert message!"); },
            showTitledAlert: function () { Dialogger.alert("This is an alert message!","Check This Out"); },
            showConfirm: function () {
                Dialogger
                    .confirm("This is a confirmation message.")
                    .then(function (result) { $scope.confirmResult = result; });
            },
            showYesNoConfirm: function () {
                Dialogger
                    .confirm("This is a Yes/No confirmation message.", null, true)
                    .then(function (result) { $scope.confirmResult = result; });
            },
            showLongConfirm: function () {
                Dialogger
                    .confirm("This is a confirmation message. This is a confirmation message. This is a confirmation message. This is a confirmation message.")
                    .then(function (result) { $scope.confirmResult = result; });
            },
            pickedDate: new Date("8/20/1972"),
            showDatePicker: function () {
                Dialogger
                    .pickDate("Please select a date:", $scope.pickedDate)
                    .then(function (result) { $scope.pickedDate = result; });
            },
            showInstPicker: function () {
                Dialogger
                    .searchInstitutions()
                    .then(function (result) {
                        $scope.selectedInsts = result;
                    });
            },
            showMultiInstPicker: function(){
                Dialogger
                    .searchInstitutions(true) //allowMultiSelect
                    .then(function (result) {
                        $scope.selectedInsts = result;
                    });
            }
        });

        activate();

        function activate() { }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .factory('DisclaimerService', DisclaimerService);

    DisclaimerService.$inject = ['$cookies', 'Idle', '$log'];

    function DisclaimerService($cookies, Idle, $log) {
        var service =
            {
                isAccepted: isAccepted,
                accept: acceptDisclaimer,
                update: updateAcceptance,
                clear: clearAcceptance
            },
            cookieVals = { key: "acceptedDisclaimer", val: "accepted" },
            refresher = null;

        return service;
        ////////////////

        function isAccepted() {
            return $cookies.get(cookieVals.key) === cookieVals.val;
        }

        function acceptDisclaimer() {
            var expiry = new Date();
            expiry.setTime(expiry.getTime() + 1000 * 60 * 60); //60 minutes
            $cookies.put(cookieVals.key, cookieVals.val, { expires: expiry });

            if(!Idle.running())
                Idle.watch();
        }

        function updateAcceptance() {
            if (service.isAccepted())
                return service.accept();
        }

        function clearAcceptance() {
            $cookies.remove(cookieVals.key);
        }
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('genericService', genericService);

    genericService.$inject = ['$http', '$log', '$uibModal', 'toastr'];

    function genericService($http, $log, $uibModal, toastr) {
        var service = {
            getStates: getStates,
            getCounties: getCounties,
            getCities: getCities,
            getSodDate: getSodDate
        };

        return service;
        ////////////////

        function getSodDate() {
            return $http.get('/api/util/getSODDate')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning SOD Date", result);
                    return "";
                });
        }

        function getStates() {
            return $http.get('/api/states/get-states-only')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning state collection data", result);
                });
        }

        function getCounties(datavalue) {
            return $http.get('/api/states/get-counties-only', { params: { stateId: datavalue } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning the counties for the following State" + data.stateId, result);
                });
        }

        //int stateId, int? countyId
        function getCities(data) {
            return $http.get('/api/states/get-cities-only', { params: { stateId: data.stateId, countyId: data.countyId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning the city for the following county" + data.stateId + ' ' + data.countyId, result);
                });
        }


       

    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .factory('GlossaryService', GlossaryService);

    GlossaryService.$inject = ['$http', '$log'];

    function GlossaryService($http, $log) {
        var url = "_jsonData/GlossaryData.json",
            service = {
                getDef: getDefinition,
                getEntries: getAllData
            };

        return service;
        ////////////////

        function getDefinition(originalTerm) {
            var term = originalTerm.toLowerCase();
            return $http.get(url, { cache: true })
                .then(function Success(result) {

                    if (_.isArray(result.data)) {
                        var match = _.find(result.data,
                            function (entry) {
                                return entry.term == term || (_.isArray(entry.term) && _.indexOf(entry.term, term) > -1);
                            });

                        if (match)
                            return match.definition;

                        $log.warn("GlossaryData.json contains no definition for '" + term + "'.");
                        return null;
                    }
                    $log.error("GlossaryData.json does not contain an array!");
                    return null;
                }, function Error() { });
        }

        function getAllData() {
            return $http.get(url)
                .then(function Success(result) {
                    if (_.isArray(result.data))
                        return result.data;

                    $log.error("GlossaryData.json does not contain an array!");
                    return [];
                },
                    function Error() { });
        }
    }
})();
;

    function clickOnEnter(id)
    {
        if (event.keyCode == 13) {            
            $("#" + id).click();
        }
    }

    function buildSearchTag(c, t, v, f)
    {
        return c != null ? t + v : f;
    }
;

(function () {
    "use strict";

    angular
      .module("app")
      .factory("InstitutionsService", InstitutionsService);

    InstitutionsService.$inject = ["$http", "$stateParams", "$log"];

    function InstitutionsService($http, $stateParams, $log) {

        var service = {
            query: search,
            search: search,
            find: find,
            get: getInstitution,
            getCommonMarkets: getCommonMarkets
        };

        return service;
        ///////////////

        function search() {
            //string name = "", int? stateId = null, int? countyId = null, int? cityId = null, string zip = "", int pageLength = -1, int pageNum = 1
            var criteria = {
                name: "",
                stateId: null,
                countyId: null,
                cityId: null,
                zip: "",
                pageLength: -1,
                pageNum: 1
            };

            if (!arguments || arguments.length === 0) return null;
            if (arguments.length === 1) {
                if (typeof arguments[0] == "object")
                    criteria = arguments[0];
                else
                    criteria.name = arguments[0];
            } else {
                criteria.name = arguments[0];
                if (arguments.length > 1) criteria.stateId = arguments[1];
                if (arguments.length > 2) criteria.countyId = arguments[2];
                if (arguments.length > 3) criteria.cityId = arguments[3];
                if (arguments.length > 4) criteria.zip = arguments[4];
                if (arguments.length > 5) criteria.pageLength = arguments[5];
                if (arguments.length > 6) criteria.pageNum = arguments[6];
            }

            return $http
                .get("/api/institutions/search", { params: criteria })
                .then(function (result) { return result.data });
        }

        function find(rssdId, data, options) {
            /*
            int rssdId, bool getDetail = false, bool getBranches = false,
            bool getOperatingMarkets = false, bool getHistory = false, string zip = null, string state = null,
            string county = null, string city = null
             */
            var params = { rssdId: rssdId };

            if(!options || !!options.getDetail) params.getDetail = true;
            if(options && !!options.getBranches) params.getBranches = true;
            if(options && !!options.getOperatingMarkets) params.getOperatingMarkets = true;
            if(options && !!options.getHistory) params.getHistory = true;

            if (data) {
                params.name = data.name;
                params.zip = data.zip;
                params.state = data.state;
                params.county = data.county;
                params.city = data.city;
            }
            else {
                if ($stateParams.name) params.name = $stateParams.name;
                if ($stateParams.zip) params.zip = $stateParams.zip;
                if ($stateParams.state) params.state = $stateParams.state;
                if ($stateParams.county) params.county = $stateParams.county;
                if ($stateParams.city) params.city = $stateParams.city;
            }

            return service.get(params);
        }

        function getInstitution() {
            //int rssdId, bool getDetail = false, bool getBranches = false, bool getOperatingMarkets = false, bool getHistory = false, 
            //, string zip = null, string state = null, string county = null, string city = null
            var criteria = {
                rssdId: null,
                getDetail: false,
                getBranches: false,
                getOperatingMarkets: false,
                getHistory: false,
                zip: null,
                state: null,
                county: null,
                city: null
            };

            if (!arguments || arguments.length === 0) return null;
            if (arguments.length === 1) {
                if (typeof arguments[0] == "object")
                    criteria = arguments[0];
                else
                    criteria.rssdId = arguments[0];
            } else {
                criteria.rssdId = arguments[0];
                if (arguments.length > 1) criteria.getDetail = arguments[1];
                if (arguments.length > 2) criteria.getBranches = arguments[2];
                if (arguments.length > 3) criteria.getOperatingMarkets = arguments[3];
                if (arguments.length > 4) criteria.getHistory = arguments[4];
                if (arguments.length > 5) criteria.zip = arguments[5];
                if (arguments.length > 6) criteria.state = arguments[6];
                if (arguments.length > 7) criteria.county = arguments[7];
                if (arguments.length > 8) criteria.city = arguments[8];
            }

            return $http
                .get("/api/institutions/get", { params: criteria, cache: true })
                .then(function (result) { return result.data });
        }

        function getCommonMarkets() {
            //string target, int buyer
            var criteria = {
                target: null,
                buyer: null
            };

            if (!arguments || arguments.length === 0 || (arguments.length === 1 && typeof arguments[0] !== "object")) return null;
            if (arguments.length === 1) {
                criteria = arguments[0];
            } else {
                criteria.rssdId = arguments[0];
                if (arguments.length > 1) criteria.getDetail = arguments[1];
                if (arguments.length > 2) criteria.getBranches = arguments[2];
                if (arguments.length > 3) criteria.getOperatingMarkets = arguments[3];
                if (arguments.length > 4) criteria.getHistory = arguments[4];
                if (arguments.length > 5) criteria.zip = arguments[5];
                if (arguments.length > 6) criteria.state = arguments[6];
                if (arguments.length > 7) criteria.county = arguments[7];
                if (arguments.length > 8) criteria.city = arguments[8];
            }

            return $http
                .get("/api/institutions/common-markets", { params: criteria })
                .then(function (result) { return result.data; });
        }
    }    

})();;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('MarketsService', MarketsService);

    MarketsService.$inject = ['$http', '$stateParams', '$log'];

    function MarketsService($http, $stateParams, $log) {
        //var statesCache = $cacheFactory('markets');
        //return $resource("/api/markets", {}, {
        //    // Enable caching
        //    get: { method: 'GET', cache: statesCache },
        //    query: { method: 'GET', cache: statesCache, isArray: true }
        //});

        var service = {
            query: search,
            search: search,
            find: find,
            get: getMarket,
            getProformaLocations: getProformaBranchLocations,
            getDistrictContact: getDistrictContact
        };

        return service;
        /////////////////////

        function search() {
            // int? stateId = null, int? countyId = null, int? cityId = null, string zip = "", int pageLength = -1, int pageNum = 1
            var criteria = {
                stateId: null,
                countyId: null,
                cityId: null,
                zip: ""
            };

            if (!arguments || arguments.length === 0) return null;
            if (arguments.length === 1) {
                if (typeof arguments[0] == "object")
                    criteria = arguments[0];
                else
                    criteria.name = arguments[0];
            } else {
                criteria.stateId = arguments[0];
                if (arguments.length > 1) criteria.countyId = arguments[1];
                if (arguments.length > 2) criteria.cityId = arguments[2];
                if (arguments.length > 3) criteria.zip = arguments[3];
            }

            return $http
                .get("/api/markets/search", { params: criteria })
                .then(function (result) { return result.data });
        }

        function find(marketId, options) {
            /*
            int marketId, bool getDefinition = false, bool getHhi = false, 
            bool getMap = false, bool getHistory = false
             */
            var params = { marketId: marketId };

            if (!options || !!options.getDefinition) params.getDefinition = true;
            if (options && !!options.getHhi) params.getHhi = true;
            if (options && !!options.getMap) params.getMap = true;
            if (options && !!options.getHistory) params.getHistory = true;

            return service.get(params);
        }

        function getMarket() {
            //int marketId, bool getDefinition = false, bool getHhi = false, 
            //  bool getMap = false, bool getHistory = false
            var criteria = {
                marketId: null,
                getDefinition: false,
                getHhi: false,
                getMap: false,
                getHistory: false
            };

            if (!arguments || arguments.length === 0) return null;
            if (arguments.length === 1) {
                if (typeof arguments[0] == "object")
                    criteria = arguments[0];
                else
                    criteria.marketId = arguments[0];
            } else {
                criteria.marketId = arguments[0];
                if (arguments.length > 1) criteria.getDefinition = arguments[1];
                if (arguments.length > 2) criteria.getHhi = arguments[2];
                if (arguments.length > 3) criteria.getMap = arguments[3];
                if (arguments.length > 4) criteria.getHistory = arguments[4];
            }

            return $http
                .get("/api/markets/get", { params: criteria, cache: true })
                .then(function (result) { return result.data });
        }

        function getProformaBranchLocations(marketId, buyer, targets, branches) {
            return $http.get("/api/markets/proformabranchlocations", { params: { marketId: marketId, buyerRssdId: buyer, targetRssdIds: targets, targetBranchIds: branches } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting proforma branch locations", result);
                });
        }
        function getDistrictContact(districtId) {
            return $http
                .get("/api/markets/get-district-contact", { params: { districtId: districtId } })
                .then(function (result) { return result.data });
        }
    }

})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .factory('MenuService', MenuService);

    MenuService.$inject = ['$http', '$rootScope', 'MENU_ROLES', 'AdminService'];

    function MenuService($http, $rootScope, MENU_ROLES, AdminService) {
        var service = {
            GetMenuLayouts: GetMenuLayouts,
            SetSelectedMenuLayout: SetSelectedMenuLayout,
            GetMenuLayoutId: GetMenuLayoutId,
            SetMenuLayoutId: SetMenuLayoutId,
            GetMSDUrl: GetMSDUrl,
            BuildMenu: BuildMenu,
            GetMenu: GetMenu,
            SetSideNavCallBk: SetSideNavCallBk,
            UpdateSideNav: UpdateSideNav,
            GetAccountExpiringSoonCount: GetAccountExpiringSoonCount
        };
        var sideNavCallBk = null;

        return service;
        ////////////////

        function GetMenuLayouts() {
            $rootScope.menuData = { menuLayout: '', selectedMenuLayout: null, menuLayoutId: 0, menuItems: [], menuLayouts: [] };
            
            return $http.get('/api/adminusers/get-menu-layouts')
                    .then(function (result) {
                        $rootScope.menuData.menuLayouts = result.data;
                    });
        }

        function SetSelectedMenuLayout(menuLayoutId) {

            $rootScope.menuData.selectedMenuLayout =
                _.find($rootScope.menuData.menuLayouts,
                    function(m) {
                        return m.menuLayoutId == menuLayoutId;
                    });

        }

        function GetAccountExpiringSoonCount() {
            return $http
                    .get('/api/admin/get-expiring-soon-count')
                    .then(function (result) {
                    return result.data;
                    });
        }


        function GetMenuLayoutId()
        {
            return $rootScope.menuData.menuLayoutId;
        }

        function SetMenuLayoutId(id)
        {
            $rootScope.menuData.menuLayoutId = id;
        }

        function GetMSDUrl() {
            return $http
                .get('/api/adminusers/get-msd-url')
                .then(function (result) {
                    return result.data;
                });
        }

        function BuildMenu(rolelist) {
            // DepInst
            // BnkMkt
            // HHIAnal
            // History
            // PendTrans
            // Reports
            // StrutChng
            // Admin
       
           // "Public": "PUBLIC",
           //"StructureAnalyst": "STRUCTURE_ANALYST_RW",
           //"UserAdmin": "ADMIN_USERACCOUNTS_RW",
           //"DataAnalyst": "DATA_ANALYST_RW",
           //"DataRefreshAdmin": "ADMIN_DATA_REFRESH_RW",
           //"MappingAnalyst": "MAPPING_ANALYST_RW",
           //"CaseWorker": "CASE_WORKER_R"
            //this is not a good solution, needs to be redone but did this on the last day of going live

            if ($rootScope.menuData.selectedMenuLayout.menuLayoutId != MENU_ROLES.StructureMaintenance) {
                if (rolelist.indexOf("STRUCTURE_ANALYST_RW") > -1)
                {
                    $rootScope.menuData.menuItems = ['DepInst', 'BnkMkt', 'HHIAnal', 'Links', 'History', 'PendTrans', 'Reports', 'StrutChng'];
                }
                else if (rolelist.indexOf("CASE_WORKER_R") > -1)
                {
                    $rootScope.menuData.menuItems = ['DepInst', 'BnkMkt', 'HHIAnal', 'Links', 'History', 'PendTrans', 'Reports'];
                }
                else if (rolelist.indexOf("DATA_ANALYST_RW") > -1)
                {
                    $rootScope.menuData.menuItems = ['BnkMkt', 'Reports', 'Links'];
                }
                else if (rolelist.indexOf("MAPPING_ANALYST_RW") > -1) {
                    $rootScope.menuData.menuItems = ['DepInst', 'Links'];
                }
                else
                {
                    $rootScope.menuData.menuItems = ['DepInst', 'BnkMkt', 'HHIAnal', 'Links', 'History', 'PendTrans', 'Reports', 'StrutChng'];
                }

                if (rolelist.indexOf("ADMIN_USERACCOUNTS_RW") > -1 || rolelist.indexOf("ADMIN_DATA_REFRESH_RW") > -1)
                {
                    $rootScope.menuData.menuItems.push('Admin', 'Quarterly');
                }
                
            }
            else {
                if (rolelist.indexOf("STRUCTURE_ANALYST_RW") > -1) {
                    $rootScope.menuData.menuItems = ['DepInst', 'StrutChng', 'History', 'PendTrans', 'Reports', 'BnkMkt', 'HHIAnal', 'Links'];
                }
                else if (rolelist.indexOf("CASE_WORKER_R") > -1) {
                    $rootScope.menuData.menuItems = ['DepInst', 'History', 'PendTrans', 'Reports', 'BnkMkt', 'HHIAnal', 'Links'];
                }
                else if (rolelist.indexOf("DATA_ANALYST_RW") > -1) {
                    $rootScope.menuData.menuItems = ['BnkMkt', 'Reports', 'Links'];
                }
                else if (rolelist.indexOf("MAPPING_ANALYST_RW") > -1) {
                    $rootScope.menuData.menuItems = ['DepInst', 'Links'];
                }
                else {
                    $rootScope.menuData.menuItems = ['DepInst', 'StrutChng', 'History', 'PendTrans', 'Reports', 'BnkMkt', 'HHIAnal', 'Links'];
                }

                if (rolelist.indexOf("ADMIN_USERACCOUNTS_RW") > -1 || rolelist.indexOf("ADMIN_DATA_REFRESH_RW") > -1) {
                    $rootScope.menuData.menuItems.push('Admin', 'Quarterly');
                }
            }

               

           
        }

        function GetMenu()
        {
            return $rootScope.menuData.menuItems;
        }

        function SetSideNavCallBk(obj)
        {
            sideNavCallBk = obj;
        }

        function UpdateSideNav() {
            if (typeof sideNavCallBk == 'function')
                sideNavCallBk();
        }

    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('NavController', NavController)
        .directive('focusVarToggleTwoWay', focusVarToggleTwoWay);

    focusVarToggleTwoWay.$inject = ['$timeout', '$parse'];

    function focusVarToggleTwoWay($timeout, $parse) {
            return {
                restrict: "A",
                link: function (scope, element, attrs)
                {
                    var model = $parse(attrs.focusVarToggleTwoWay);
                    scope.$watch(model, function (value)
                    {
                        if (value === true) { $timeout(function () { element[0].focus(); });}
                    });
                    element.bind('blur', function () { if (model && model.assign) { scope.$apply(model.assign(scope, false)); }});
                }
            };
        };

    NavController.$inject = ['$scope', '$rootScope', 'AuthService', 'DataSetService', '$state', '$stateParams', '$window', '$http', '$location', 'config', '$log', '$cookies', 'toastr', 'MenuService', 'AuthService', 'APP_ROLES'];

    function NavController($scope, $rootScope, Auth, DataSets, $state, $stateParams, $window, $http, $location, config, $log, $cookies, toastr, MenuService, AuthService, ROLES) {
        angular.extend($scope,
        {
            isLoggedIn: Auth.isLoggedIn(),
            toggleSideNav: handleToggleSideNav,
            launchPrintLayout: launchPrintLayout,
            enablePrinting: !config.print,
            showHideDatasetSelect: showHideDatasetSelect,
            toggleDatasetSelect: toggleDatasetSelect,
            dataSetChanged: handleDataSetChanged,
            dataSets: [],
            selectedDataSet: null,
            updatingDataSet: false,                  
            inArchiveDataset: false,
            accountsExpiringSoonCount: 0
        });     

        activate();

        function activate() {
            //NOTE: If you auto-print here, it will be too soon b/c data will not have loaded yet. DON'T DO IT!
            //if (config.print === true)
            //    $window.print();

            $rootScope.accountsExpiringSoonCount = 0;

            $scope.$watch('$root.accountsExpiringSoonCount', function () {
                $scope.accountsExpiringSoonCount = $rootScope.accountsExpiringSoonCount;
            });

            if (AuthService.isAllowed(ROLES.UserAdmin)) {
                MenuService.GetAccountExpiringSoonCount().then(function (result) { $rootScope.accountsExpiringSoonCount = result; });
            }

            DataSets.query().$promise.then(function (result) {
                $rootScope.dataSets = result;
                $rootScope.dataSet = _.find(result, { isUserChoice: true });
                if ($rootScope.dataSet == null || typeof $rootScope.dataSet == 'undefined') { $rootScope.dataSet = [];}
                $scope.dataSets = $rootScope.dataSets;
                $scope.selectedDataSet = $rootScope.dataSet;
            });

            $scope.showNavDatasetSelect = false;          

            if ($cookies.get('sideNavCollapsed') != null) {
                $rootScope.sideNavCollapsed = $cookies.get('sideNavCollapsed') == "true";
            }
            else {
                $rootScope.sideNavCollapsed = false;
            }

            
            if (config.print === true) {
                $scope.enablePrinting = false;
                $scope.printDate = config.printDate;
                $rootScope.$watch(function() {
                        return $http.pendingRequests.length > 0;
                    },
                    function(hasPending) {
                        if (hasPending) {
                            // show wait dialog
                        } else {
                            //$window.print(); //NOTE: ALMOST! Must wait another second (or so) b/c page is not yet fully rendered right when data is returned.
                            $scope.enablePrinting = true;
                            // hide wait dialog
                        }
                    });
            } else {
                $scope.enablePrinting = true;
            }
        }

        function handleDataSetChanged() {
            $scope.updatingDataSet = true;
            DataSets.save({ id: $scope.selectedDataSet.id }, {},
                function Success() {
                    $log.info("SUCCESS!");
                    $rootScope.dataSet.isUserChoice = false; // for consistency's sake, but not really needed

                    $rootScope.dataSet = $scope.selectedDataSet;
                    $rootScope.dataSet.isUserChoice = true;

                    $scope.updatingDataSet = false;

                    // rebuild the menu with the roles after dataset change
                    var returningToLive = ($scope.selectedDataSet.name.toUpperCase() === "LIVE" || $scope.selectedDataSet.id.toUpperCase() === "LIVE");
					Auth.getUserRoleFormalNames(returningToLive).then(function (result) {
						MenuService.BuildMenu(result.data);
						MenuService.UpdateSideNav();
						if (returningToLive) {
							$("#header-container").removeClass("archiveData");
						}
						else {
							$("#header-container").addClass("archiveData");
						}

						toastr.success("Your dataset was updated successfully.");
						$scope.showNavDatasetSelect = false;

						// go to the homepage so that we reload everything
						$state.go("root.adv.index");
						//window.location.reload(); // = "/advanced/index";
					});

					// moved this into the .then function
                    //if (returningToLive) {
                    //    $("#header-container").removeClass("archiveData");
                    //}
                    //else {
                    //    $("#header-container").addClass("archiveData");
                    //}

                    //toastr.success("Your dataset was updated successfully.");
                    //$scope.showNavDatasetSelect = false;

                    // go to the homepage so that we reload everything
                    //$state.go("root.adv.index");
                    //window.location = "/advanced/index";

                },
                function Failure() {
                    $log.info("FAILURE!");
                    toastr.error("The dataset you selected does not exist, please contact your administrator.");
                    $scope.selectedDataSet = $rootScope.dataSet;

                    $scope.updatingDataSet = false;
                });
        }

        function toggleDatasetSelect() {
            showHideDatasetSelect(!$scope.showNavDatasetSelect);
        }

        function showHideDatasetSelect(selectIsVisible)
        {
            $scope.showNavDatasetSelect = selectIsVisible;
        }

        function handleToggleSideNav() {
            $rootScope.sideNavCollapsed = !$rootScope.sideNavCollapsed;

            $cookies.put('sideNavCollapsed', $rootScope.sideNavCollapsed);
            //$log.info("sideNavCollapsed", $rootScope.sideNavCollapsed);
        }

        function launchPrintLayout() {
            //NOTE: This works but is not as flexible, nor is it very Angular:
            //var newUrl = $location.url();
            //if (newUrl.indexOf("?") > -1)
            //    newUrl += "&print";
            //else
            //    newUrl += "?print";
            //$window.open(newUrl);

            if (config.print === true) {
                if ($scope.enablePrinting)
                    $window.print();
            } else {
                var params = $stateParams;
                params.print = true;
                var newUrl = $state.href($state.current.name, params, { absolute: true });
                //$log.info("newUrl", newUrl);
                $window.open(newUrl);
            }
        }
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('NewsService', NewsService);

    NewsService.$inject = ['$resource', '$cookies'];

    function NewsService($resource, $cookies) {

        var cookie_key = "dismissed-news";

        var service = {
            data: $resource("/api/news/:newsId", { newsId: '@id' }),
            getDismissedNewsIds: getNewsIds,
            dismissByNewsId: dismissNewsItem
        };

        return service;

        function getNewsIds() {
            var cookie_value = $cookies.get(cookie_key),
                newsIds = cookie_value ? JSON.parse(cookie_value) : [];

            if (!angular.isArray(newsIds)) newsIds = [];

            return newsIds;
        }

        function saveNewsIds(newsIds) {
            var expiry = new Date();
            expiry.setDate(expiry.getDate() + 10000);
            $cookies.put(cookie_key, JSON.stringify(newsIds), { expires: expiry });
        }

        function dismissNewsItem(newsId) {
            var newsIds = getNewsIds();
            newsIds.push(newsId);
            saveNewsIds(newsIds);
        }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('SidebarController', SidebarController)
        .filter('errorSBFilter', function () {
         return function (errors, buyerRSSD, targetRSSD) {
             var out = [];
             var bRSSD = null;
             if (buyerRSSD.length > 0) bRSSD = buyerRSSD[0].rssdId;

             if (buyerRSSD.length > 0 && targetRSSD.length > 0) {
                 for (var i = 0; i < targetRSSD.length; i++) {
                     if (targetRSSD[i].rssdId == bRSSD) {
                         angular.forEach(errors, function (item) {
                             if (item.isBTMatch) {
                                 out.push(item)
                             }
                         });
                     }
                 }

             }
             if (buyerRSSD.length > 0 && targetRSSD.length > 0) {
                 var parentRSSDIds = [];
                 for (var i = 0; i < targetRSSD.length; i++) {
                     if (buyerRSSD[0].class == "BHC" && buyerRSSD[0].parentId == targetRSSD[i].parentId && buyerRSSD[0].rssdId != targetRSSD[i].rssdId) {
                         angular.forEach(errors, function (item) {
                             if (item.isHoldSub) {
                                 out.push(item)
                             }
                         });
                     }
                     else if (buyerRSSD.parentId == targetRSSD[i].parentId && buyerRSSD.rssdId != targetRSSD[i].rssdId) {
                         angular.forEach(errors, function (item) {
                             if (item.isTopholdMatch) {
                                 out.push(item)
                             }
                         });
                     }
                     if (_.indexOf(parentRSSDIds, targetRSSD[i].parentId) == -1) {
                         parentRSSDIds.push(targetRSSD[i].parentId);
                     }
                     else {
                         angular.forEach(errors, function (item) {
                             if (item.isTargetTopSub) {
                                 out.push(item)
                             }
                         });
                     }
                     if (buyerRSSD[0].class != "BHC" && targetRSSD[i].class == "BHC") {
                         angular.forEach(errors, function (item) {
                             if (item.isTargetHoldNotBuyer) {
                                 out.push(item)
                             }
                         });
                     }
                     if (buyerRSSD[0].class != "BHC" && targetRSSD[i].branchCount > 0) {
                         angular.forEach(errors, function (item) {
                             if (item.isTargetWBranches) {
                                 out.push(item)
                             }
                         });
                     }
                 }

             }

             return out;
         }
     });

    SidebarController.$inject = ['$scope', '$rootScope', 'UserData' ,'$state', 'ProFormaService'];

    function SidebarController($scope, $rootScope, UserData, $state, ProFormaService) {
        $scope.UserData = UserData;
        $scope.errorsSB = [
            { name: "sameBuyerTarget", error: "Warning: You have saved the same institution as both the buyer and target.", isBTMatch: true, isTopholdMatch: false, isHoldSub: false, isTargetTopSub: false, isTargetHoldNotBuyer: false, isTargetWBranches: false },
            { name: "sameControl", error: "Warning: You have saved a buyer and target that are under the same holding company.", isBTMatch: false, isTopholdMatch: true, isHoldSub: false, isTargetTopSub: false, isTargetHoldNotBuyer: false, isTargetWBranches: false },
            { name: "targetControlByBuyer", error: "Warning: You have saved a holding company, and one of its subsidiaries.", isBTMatch: false, isTopholdMatch: false, isHoldSub: true, isTargetTopSub: false, isTargetHoldNotBuyer: false, isTargetWBranches: false },
            { name: "targetTopAndSub", error: "Warning: you have saved a holding company and one of its subsidiaries.", isBTMatch: false, isTopholdMatch: false, isHoldSub: false, isTargetTopSub: true, isTargetHoldNotBuyer: false, isTargetWBranches: false },
            { name: "targetHold", error: "Warning: you have saved an institution as a buyer of a holding company. Please select a holding company as the buyer.", isBTMatch: false, isTopholdMatch: false, isHoldSub: false, isTargetTopSub: false, isTargetHoldNotBuyer: true, isTargetWBranches: false },
            { name: "topHoldBranch", error: "*** A holdings company has been selected as the buyer for a purchase of branches from a target.  Please select a bank or thrift as the buyer.", isBTMatch: false, isTopholdMatch: false, isHoldSub: false, isTargetTopSub: false, isTargetHoldNotBuyer: false, isTargetWBranches: true },
        ];

        $scope.clearAll = function () {

            UserData.buyerInstitutions.reset();
            UserData.targetInstitutions.reset();
        }

        $scope.clearSavedMarkets = function () {
            UserData.markets.reset();
        };


        $scope.viewCommonMarkets = function () {
            var buyer = UserData.buyerInstitutions.get()[0].rssdId,
                targets = _.join(_.flatMap(_.filter(UserData.targetInstitutions.get(), function (e) { return e.branches == null || e.branches.length == 0 }), "rssdId"), ","),
                branches = _.join(_.flatMap(UserData.targetInstitutions.get(), function (target) { return _.flatMap(target.branches, function (e) { return e.branchId }) }));

            $state.go('root.analysis.common-markets', { buyer: buyer, targets: targets, branches: branches });
        }


        $scope.getErrors = function() {

            if (UserData.buyerInstitutions.get().length > 0) {
                var errors = ProFormaService.runErrorCheck(UserData.buyerInstitutions.get()[0], UserData.targetInstitutions.get());

                return errors;
            }

            return [];
        };

        activate();

        function activate() { }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('StatesController', StatesController)
        
    StatesController.$inject = ['$scope', '$rootScope', 'UserData', '$state'];

    function StatesController($scope, $rootScope, UserData, $state) {
       

        activate();

        function activate() { }
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('StatesService', StatesService);

    StatesService.$inject = ['$http', '$log', '$resource', '$cacheFactory'];

    function StatesService($http, $log, $resource, $cacheFactory) {
        var statesCache = $cacheFactory('states');
        var service = $resource("/api/states", {}, {
            // Enable caching
            get: { method: 'GET', cache: statesCache },
            query: { method: 'GET', cache: statesCache, isArray: true },
            //getInternationalCities: { method: 'GET', cache: statesCache }
        });




        var statesPromise = service.query().$promise;

        return {
            service: service,
            statesPromise: statesPromise,
            reload: reloadStates,
            getStateId: getStateIdByStateName,
            getState: getStateByStateId,
            getCountyId: getCountyIdByCountyName,
            getCounty: getCountyByCountyId,
            getCityId: getCityIdByCityName,
            getCity: getCityByCityId,
            getInternationalCities: getInternationalCities,
            getStatesWithDistricts: getStatesWithDistricts,
            getStateSummaries: getStateSummaries,
            getCountySummaries: getCountySummaries,
            getCitySummaries: getCitySummaries,
            getCountySubdivisionSummaries: getCountySubdivisionSummaries,
            getCityNames: getCityNames,
            getCitiesOnly: getCitiesOnly,
            getSingleCity: getSingleCity,
            getNations: getNations,
            getNationCities: getNationCities,
            getStateCapPercent: getStateCapPercent
        }

        function getStateCapPercent(stateInfo) {
            return $http.get('/api/analysis/get-state-cap-percent', { params: { stateId: stateInfo.fipsId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning state deposit cap data", result);
                });
        }
        function reloadStates() {
            statesPromise = service.query().$promise;
        }

        function getStateIdByStateName(stateName, states) {
            var state = _.find(states, { state: stateName });
            return state.stateId;
        }

        function getStateByStateId(stateId, states) {
            var state = _.find(states, { stateId: stateId });
            return state;
        }

        function getCountyIdByCountyName(countyName, counties) {
            var county = _.find(counties, { county: countyName });
            return county.countyId;
        }

        function getCountyByCountyId(countyId, counties) {
            var county = _.find(counties, { countyId: countyId });
            return county;
        }

        function getCityIdByCityName(cityName, cities) {
            var city = _.find(cities, { city: cityName });
            return city.cityId;
        }

        function getCityByCityId(cityId, cities) {
            var city = _.find(cities, { cityId: cityId });
            return city;
        }

        function getInternationalCities() {
            return $http.get('/api/states/get-international-cities')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning international cities data", result);
                });
        }

        function getNations(requireCityExists) {
            return $http.get('/api/states/get-nations', { params: { requireCitiesExist: requireCityExists} })
               .then(function Success(result) {
                   return result.data;
               }, function Failure(result) {
                   $log.error("Error returning list of nations", result);
               });
        }

        function getNationCities(nationId) {
            return $http.get('/api/states/get-nation-cities', { params: { nationId: nationId } })
               .then(function Success(result) {
                   return result.data;
               }, function Failure(result) {
                   $log.error("Error returning list of cities", result);
               });
        }

        function getStatesWithDistricts() {
            return $http.get('/api/states/get-states-with-districts')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning states by counties data", result);
                });
        }
        function getStateSummaries(data) {
            return $http.get('/api/states/get-state-summaries', { params: { includeDC: data.includeDC, includeTerritories: data.includeTerritories} })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning states summaries data", result);
                });
        }
        function getCountySummaries(data) {
            return $http.get('/api/states/get-county-summaries', { params: { stateFIPSId: data.stateFIPSId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning counties summaries by state data", result);
                });
        }
        function getCitySummaries(data) {
            return $http.get('/api/states/get-city-summaries', { params: { countyId: data.countyId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning counties summaries by state data", result);
                });
        }
        function getCityNames(data) {
            return $http.get('/api/states/get-city-names', { params: { stateFIPSId: data.stateFIPSId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning city names by state data", result);
                });
        }
        function getSingleCity(data) {
            return $http.get('/api/states/get-single-city', { params: { cityName: data.cityName, countyId: data.countyId, stateFipsId: data.stateFipsId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning city information", result);
                });
        }
        function getCitiesOnly(stateId) {
            return $http.get('/api/states/get-cities-only', { params: { stateId: stateId, countyId: '' } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning city information", result);
                });
        }
        function getCountySubdivisionSummaries(data) {
            return $http.get('/api/states/get-subdivision-summaries', { params: { countyId: data.countyId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning counties summaries by state data", result);
                });
        }

    }

})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('UserData', UserData);

    UserData.$inject = ['UserService', '$log'];

    function UserData(UserService, $log) {
        var emptyDataStruc = { markets: [], buyerInstitutions: [], targetInstitutions: [], institutions: [] }

        var dataKey = "user-data-storage-key",
            data = getStoredUserData(emptyDataStruc),
            profile = UserService.get();

        var service = {
            markets: {
                save: saveMarket,
                get: getMarkets,
                isSaved: isSavedMarket,
                remove: removeMarket,
                any: hasMarkets,
                hasMarket: hasMarket,
                reset: clearMarkets,
                simplify: simplifyMarket
            },
            buyerInstitutions: {
                save: saveBuyerInstitution,
                get: getBuyerInstitutions,
                isSaved: isSavedBuyerInstitution,
                remove: removeBuyerInstitution,
                any: hasBuyerInstitutions,
                reset: clearBuyerInstitutions,
                getID: getBuyerInstitutionsRSSDId,
                simplify: simplifyInstitution
            },
            targetInstitutions: {
                save: saveTargetInstitution,
                get: getTargetInstitutions,
                isSaved: isSavedTargetInstitution,
                remove: removeTargetInstitution,
                any: hasTargetInstitutions,
                reset: clearTargetInstitutions,
                simplify: simplifyInstitution,
                saveBranch: saveTargetBranch,
                isSavedBranch: isSavedTargetBranch,
                removeBranch: removeTargetBranch,
                toggleBranch: toggleTargetBranch
            },
            institutions: {
                save: saveInstitution,
                get: getInstitutions,
                isSaved: isSavedInstitution,
                remove: removeInstitution,
                any: hasInstitutions,
                reset: clearInstitutions,
                simplify: simplifyInstitution,
                removebyID: removeInstitutionbyID,
                saveBranch: saveInstitutionBranch,
                isSavedBranch: isSavedBranch,
                removeBranch: removeBranch,
                toggleBranch: toggleBranch,
                findSavedInstitution: findInstitution
            },
            dataObject: {
            reset: clearAllUserData
        }
        };

        return service;
        ////////////////

        // Markets...

        function simplifyMarket() { /* (marketObject:object) -OR- (marketId:number, marketName:string) -OR- (marketName:string, marketId:number) */
            if (typeof arguments[0] == "object") {
                var m = arguments[0];
                if ((m.marketId || m.marketNumber || m.id || m.number) && (m.name || m.marketName)) {
                    var market = {
                        marketId: m.marketId || m.marketNumber || m.id || m.number,
                        marketName: m.name || m.marketName
                    };
                    if (typeof market.marketId == "number" && typeof market.marketName == "string")
                        return market;
                }
            } else if (arguments.length > 1) {

                if (typeof arguments[0] == "number" && typeof arguments[1] == "string")
                    return {
                        marketId: arguments[0],
                        marketName: arguments[1]
                    };
                else if (typeof arguments[1] == "number" && typeof arguments[0] == "string")
                    return {
                        marketId: arguments[1],
                        marketName: arguments[0]
                    };
            }
            return null;
        }

        function saveMarket() { /* (marketObject:object) -OR- (marketId:number, marketName:string) -OR- (marketName:string, marketId:number) */
            var market = simplifyMarket.apply(undefined, arguments);
            if (market) {
                var id = market.marketId;
                if (!isSavedMarket(id)) {
                    data.markets.push(market);
                    data.markets.sort(function (a, b) {
                        return a.marketName < b.marketName
                            ? -1
                            : a.marketName > b.marketName
                                ? 1
                                : 0;
                    });
                    storeUserData();
                }
                return true;
            } else
                $log.error("No market saved");
            return false;
        }

        function getMarkets() {
            return data.markets;
        }

        function isSavedMarket(id) {
            return _.findIndex(data.markets, { marketId: id }) > -1;
        }

        function removeMarket(id) {
            if (!angular.isArray(id)) id = [id];
            _(id).forEach(function (i) {
                if (typeof i == "object")
                    _.remove(data.markets, { marketId: i.marketId });
                else
                    _.remove(data.markets, { marketId: i });
            });

            storeUserData();
        }

        function clearMarkets() {
            data.markets = [];
            storeUserData();
        }

        function hasMarkets(marx) {
            if (!data.markets) return false;
            if (typeof marx != "undefined") {
                if (!angular.isArray(marx)) marx = [marx];
                return _.intersectionBy(data.markets, marx, "marketId").length > 0;
            }
            return data.markets.length > 0;
        }

        function hasMarket() {
            return data.markets.length > 0;
        }

        // Buyer Institutions...

        function saveBuyerInstitution(inst) {
            inst = simplifyInstitution(inst);
            if (inst) {
                clearBuyerInstitutions();
                data.buyerInstitutions.push(inst);
                storeUserData();
                return true;
            } else
                $log.error("Buyer not saved");
            return false;
        }

        function getBuyerInstitutions() {
            return data.buyerInstitutions;
        }

        function getBuyerInstitutionsRSSDId() {
            return data.buyerInstitutions[0].rssdId;
        }

        function isSavedBuyerInstitution(inst) {
            return _.find(data.buyerInstitutions, { rssdId: inst.rssdId }) != null;
            //return _.indexOf(data.buyerInstitutions, inst) > -1;
        }

        function removeBuyerInstitution(inst) {

            _.pull(data.buyerInstitutions, _.find(data.buyerInstitutions, { rssdId: inst.rssdId }));
            storeUserData();
        }

        function clearBuyerInstitutions() {
            data.buyerInstitutions = [];
            storeUserData();
        }

        function hasBuyerInstitutions() {
            return data.buyerInstitutions && data.buyerInstitutions.length > 0;
        }

        // Target Institutions

        function saveTargetInstitution(inst) {
            inst = simplifyInstitution(inst);
            if (inst) {
                if (!isSavedTargetInstitution(inst)) {
                    data.targetInstitutions.push(inst);
                    storeUserData();
                } else {
                    if (inst.branches) {
                        _.forEach(inst.branches, function(e) { saveTargetBranch(e) });
                    }
                }
                return true;
            } else
                $log.error("Target not saved");
            return false;
        }

        function saveTargetBranch(branch) {

            var inst = _.find(data.targetInstitutions, { rssdId: branch.rssdId });
            if (inst) {
                if (!isSavedTargetBranch(branch)) {
                    inst.branches.push(fnMakeSimpleBranch(branch));
                    storeUserData();
                }
                return true;
            } else
                $log.error("Target Branch not saved");
            return false;
        }

        function isSavedTargetBranch(branch) {
            var inst = _.find(data.targetInstitutions, { rssdId: branch.rssdId });

            if (!inst)
                return false;

            return _.find(inst.branches, { branchId: branch.branchId });
        }

        function getTargetInstitutions() {
            return data.targetInstitutions;
        }

        function isSavedTargetInstitution(inst) {
            return _.find(data.targetInstitutions, { rssdId: inst.rssdId }) != null;
        }

        function removeTargetInstitution(inst) {
            _.pull(data.targetInstitutions, _.find(data.targetInstitutions, { rssdId: inst.rssdId }));
            storeUserData();
        }

        function removeTargetBranch(branch) {

            var inst = _.find(data.targetInstitutions, { rssdId: branch.rssdId });
            _.pull(inst.branches, _.find(inst.branches, { branchId: branch.branchId }));

            storeUserData();
        }

        function toggleTargetBranch(inst, branch) {
            if (isSavedTargetInstitution(inst)) {
                if (isSavedTargetBranch(branch)) {
                    removeTargetBranch(branch);
                } else {
                    saveTargetBranch(branch);
                }
            } else {
                saveTargetInstitution(inst);
                saveTargetBranch(branch);
            }
        }

        function clearTargetInstitutions() {
            data.targetInstitutions = [];
            storeUserData();
        }

        function hasTargetInstitutions() {
            return data.targetInstitutions && data.targetInstitutions.length > 0;
        }

        // Institutions ...

        function simplifyInstitution(bigInst) { /* (institutionObject:object) -OR- (rssdId:number, name:string, city:string, state:string) */
            //$log.info("bigInst", bigInst);
            if (typeof bigInst == "object") {
                if (bigInst.rssdId && bigInst.parentId && bigInst.name && bigInst.class && bigInst.city && (typeof bigInst.branchCount != "undefined") && bigInst.orgs) {
                    var inst = fnMakeSimpleInst(bigInst, true);
                    return inst;
                }
            }
            return null;

            function fnMakeSimpleInst(i, addOrgs) {
                var i2 = {
                    rssdId: i.rssdId,
                    parentId: i.parentId,
                    name: i.name,
                    "class": i.class,
                    city: i.city,
                    stateCode: i.stateCode,
                    branchCount: i.branchCount,
                    branches: _.map(i.branches, fnMakeSimpleBranch)
                };

                if (addOrgs === true)
                    i2.orgs = _.map(i.orgs, fnMakeSimpleInst);

                return i2;
            }


         
        }

        function fnMakeSimpleBranch(i) {
            var i2 = {
                rssdId: i.rssdId,
                branchId: i.branchId,
                cassidiId: i.cassidiId,
                firmat: i.firmatBranchId,
                facility: i.facility,
                address: i.address,
                name: i.name,
                city: i.city,
                state: i.state
            };

            return i2;
        }

        function saveInstitution(inst) {
            inst = simplifyInstitution(inst);
            if (inst) {

                var foundInst = _.find(data.institutions, { rssdId: inst.rssdId });

                if (!foundInst) {
                    data.institutions.push(inst);
                    storeUserData();
                } else if (inst.orgs.length > 0) {

                    _.each(inst.orgs, function (e) {

                        var foundOrg = _.find(foundInst.orgs, { rssdId: e.rssdId });

                        if (!foundOrg)
                            foundInst.orgs.push(e);
                    });

                  

                }
                return true;
            } else
                $log.error("No institution save");
            return false;
        }

        function getInstitutions() {
            return data.institutions;
        }

        function isSavedInstitution(inst) {

            var foundInst = _.find(data.institutions, { rssdId: inst.rssdId });
            var returnValue = false;

            if (foundInst)
                return true;

            _.each(data.institutions,
                function (e) {
                    foundInst = _.find(e.orgs, { rssdId: inst.rssdId });

                    if (foundInst) {
                        returnValue = true;
                    }

                });


            return returnValue;
        }

        function removeInstitution(inst) {
            _.pull(data.institutions, inst);
            storeUserData();
        }

        function removeInstitutionbyID(id) {
            _.remove(data.institutions, { rssdId: id });
            storeUserData();
        }



        function clearInstitutions() {
            data.institutions = [];
            storeUserData();
        }

        function hasInstitutions() {
            return data.institutions && data.institutions.length > 0;
        }

        function saveBranch(branch) {

            var inst = _.find(data.institutions, { rssdId: branch.parentRssdId });
            if (inst) {
                if (!isSavedBranch(branch)) {
                    inst.branches.push(fnMakeSimpleBranch(branch));
                    storeUserData();
                }
                return true;
            } else
                $log.error("Branch not saved");
            return false;
        }

        function isSavedBranch(branch) {

            var foundInst = findInstitution(branch.parentRssdId);

            if (!foundInst)
                return false;

            return _.find(foundInst.branches, { branchId: branch.branchId });

        }

        function removeBranch(branch) {

            var inst = _.find(data.institutions, { rssdId: branch.parentRssdId });
            _.pull(inst.branches, _.find(inst.branches, { branchId: branch.branchId }));

            storeUserData();
        }

        function toggleBranch(inst, branch) {
            if (isSavedInstitution(inst)) {
                if (isSavedBranch(branch)) {
                    removeBranch(branch);
                } else {
                    saveBranch(branch);
                }
            } else {
                saveInstitution(inst);
                saveBranch(branch);
            }
        }


        function findInstitution(rssdId) {

            var result = null;
            var inst = _.find(data.institutions, { rssdId: rssdId });

            if (inst) {
                result = inst;
            } else {
                _.each(data.institutions,
                    function(e) {
                        var org = _.find(e.orgs, { rssdId: rssdId });

                        if (org)
                            result = org;
                    });
            }

            //if (!result)
            //    $log.error("Insitution not found");

            return result;
        }


        function saveInstitutionBranch(branch) {

            var inst = findInstitution(branch.parentRssdId);

            if (inst) {
                if (!_.find(inst.branches, { branchId: branch.branchId })) {
                    inst.branches.push(fnMakeSimpleBranch(branch));
                    storeUserData();
                }
                return true;
            } else
                $log.error("Target Branch not saved");
            return false;
        }

        // Storage
        function storeUserData() {
            sessionStorage[dataKey] = JSON.stringify(data);
        }

        function clearAllUserData()
        {
            //sessionStorage.clear();
            //storeUserData(emptyDataStruc);
            sessionStorage.removeItem(dataKey);
        }

        function hasStoredUserData() {
            return !!sessionStorage[dataKey];
        }

        function getStoredUserData(starterObject) {
            if (hasStoredUserData()) {
                var userDataString = sessionStorage[dataKey];
                return JSON.parse(userDataString);
            }
            return starterObject;
        }


    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('UserService', UserService);

    UserService.$inject = ['$resource'];

    function UserService($resource) {
        var service = $resource("/api/userprofile/:userId", {userId: '@userId'});
        //var User = $resource('/user/:userId', { userId: '@id' });
        //var user = User.get({ userId: 123 }, function () {
        //    user.abc = true;
        //    user.$save();
        //});

        return service;
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('UtilityService', UtilityService);

    UtilityService.$inject = ['$http'];

    function UtilityService($http) {
        var service = {
            contactUs: contactUs,
            toTitleCase: toTitleCase,
            IsDateString: IsDateString
        };

        return service;
        ////////////////

        function contactUs(data) { //email, comments) {
            //var data = { email: email, comments: comments };
            return $http
                .post('/api/util/contact-us', data)
                .then(function (result) {
                    return result.data;
                });
        }

        function toTitleCase(str) {
            return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
        }

        function IsDateString(data) {

            return $http
                .get('/api/util/date-validator', { params: { dateString: data.dateString } })
                .then(function (result) {
                    return result.data;
                });
        }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('ViewController', ViewController);

    ViewController.$inject = ['$scope', '$rootScope', '$state', '$urlRouter', '$uibModal', 'UserData', 'UtilityService', 'toastr', 'Idle'];

    function ViewController($scope, $rootScope, $state, $urlRouter, $uibModal, UserData, Util, toastr, Idle) {
        $scope.isFirstPageLoad = true;

        $scope.$on("$viewContentLoading", function (event, viewConfig) {
            if ($scope.isFirstPageLoad) {
                //$("li.active").removeClass("active");
                $scope.isFirstPageLoad = false;

                //IMPORTANT: Browser Forward/Back won't work if we don't do this.
                $urlRouter.listen();
            }
        });

        var idleWarningModal = null, timedOutModal = null;
        function closeIdleModals() {
            if (idleWarningModal) {
                idleWarningModal.close();
                idleWarningModal = null;
            }
            if (timedOutModal) {
                timedOutModal.close();
                timedOutModal = null;
            }
        }
        $scope.$on("IdleStart", function () {
            closeIdleModals();
            idleWarningModal = $uibModal.open({ templateUrl: "AppJs/common/tpls/idleWarningModal.html", windowClass: "cassidi-standard-modal alert" });
        });

        $scope.$on("IdleEnd", function () {
            closeIdleModals();
        });

        $scope.$on("IdleTimeout", function () {
            closeIdleModals();
            var lastState = $state.current;
            $state.go("root.logout");
            timedOutModal = $uibModal.open({
                templateUrl: "AppJs/common/tpls/idleTimedoutModal.html",
                windowClass: "cassidi-standard-modal alert",
                controller: ["$scope", "$state", function ($scope, $state) {
                    $scope.goBack = function () {
                        $state.go(lastState.name, lastState.params);
                    };
                }]
            });
        });

        $scope.openContactUsForm = function () {
            $uibModal.open({
                animation: true,
                templateUrl: 'AppJs/common/tpls/contactUsModal.html',
                controller: ['$scope', "$uibModalInstance", "AuthService", function ($scope, $uibModalInstance, Auth) {
                    console.log(Auth.details);
                    $scope.email = Auth.details.email;
                    $scope.emailReadOnly = Auth.details.email && Auth.details.email.length > 3;
                    $scope.comments = "";
                    //$scope.feedbackType = "General";
                    $scope.sendFeedback = function () {
                        $uibModalInstance.close({ email: $scope.email, comments: $scope.comments }); //, feedbackType: $scope.feedbackType });
                    };
                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };
                }]
            }).result.then(function (result) {
                Util.contactUs(result)
                    .then(function (response) {
                        console.log("response", response);
                        if (response.isOk)
                            toastr.success("Your message was sent!");
                        else
                            toastr.error("There was an unexpected error.", response.error || "Please try again or contact support. Sorry about that.");
                    }, function (err) {
                        alert("Sorry. There was an error.");
                    });
            }, function () {
                //dismissed
            });
        };

        $scope.opentermsOfUseModal = function () {
            $uibModal.open({
                animation: true,
                templateUrl: 'AppJs/common/tpls/termsOfUseModal.html',
                controller: function ($scope, $uibModalInstance) {
                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };
                }
            });
        };

        $scope.showingSidebar = function () {
            return (UserData.markets.any() || UserData.buyerInstitutions.any() || UserData.targetInstitutions.any())
                && (!$state.current.data || $state.current.data.isAdvanced === false);
        };
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .factory('AuthService', AuthService);

    AuthService.$inject = ['$http', '$rootScope', '$uibModal', '$log', 'UserData'];

    function AuthService($http, $rootScope, $uibModal, $log, UserData) {
        var service = {
            check: check,
            updateMenuLayout: updateMenuLayout,
            login: login,
            logout: logout,
            details: {},
            isLoggedIn: isLoggedIn,
            isLoggedInAsync: isLoggedInAsync,
            GetRoleFriendlyNames: GetRoleFriendlyNames,
            getUserRoleFormalNames : GetUserRoleFormalNames,
            isAuthorized: isAuthorized,
            changePassword: changePassword,
            isAllowed: isAllowed,
            openPassChangeModal: openPassChangeModal,
            rolesName: {}
        };

        return service;
        ////////////////

        function check() {
            $http
                .get('/api/auth/check')
                .then(function (result) {
                    service.details = result.data;
                    return result.data.isOk;
                });
        }

        function updateMenuLayout(menuLayoutId) {
            $http
                .get('/api/auth/update-menulayout?menuLayoutId=' + menuLayoutId)
                .then(function (result) {
                    service.details = result.data;
                    return result.data.isOk;
                });
        }

        function login(u, p) {
            var authData = typeof u == "undefined" ? null : { userName: u, password: p || "" };
            return $http
                .post('/api/auth/login', authData)
                .then(function (result) {
                    service.details = result.data;
                    if (result.data.isAuthenticated) $rootScope.$broadcast("auth.login");
                    return result.data;
                });
        }

        function logout() {
            // clear out the client-side session data stored by the user
            UserData.dataObject.reset();

            // do the server-side logout
            return $http
                .get('/api/auth/logout')
                .then(function (result) {
                    service.details = result.data;
                    if (result.data.isOk) $rootScope.$broadcast("auth.logout");
                    return result.data.isOk;
                });
        }

		function isLoggedIn(useNewFormsAuth) {
			// original check
			var hasCurrentLoginStatus = service.details !== undefined && service.details.isOk === true && service.details.isAuthenticated === true;

			// mod for forms auth in secondary window
			if (!hasCurrentLoginStatus && useNewFormsAuth === true) {
				hasCurrentLoginStatus = isLoggedInAsync();
			}

			return hasCurrentLoginStatus;		
		}

        function isLoggedInAsync() {
            return $http
                .get('/api/auth/check')
                .then(function (result) {
                    return result.data.isAuthenticated === true;
                });
        }

        function GetRoleFriendlyNames(data) {
            return $http
                .get('/api/auth/rolesfriendlyname', { params: { names: data} })
                .then(function (result) {
                    return result;
                });
        }

        function GetUserRoleFormalNames(refreshFromDBFlag) {
            return $http
                .get('/api/auth/userRoleNames', { params: {refreshFromDB: refreshFromDBFlag}})
                .then(function (result) {
                    return result;
                });
        }

        function isAuthorized() {
            var hasPublicRole = isAllowed("PUBLIC");

            return service.isLoggedIn() &&
                _.isArray(service.details.roles) &&
                (hasPublicRole && service.details.roles.length > 1) ||
                (!hasPublicRole && service.details.roles.length > 0);
        }

        function changePassword(oldPassword, newPassword, userName) {

            var data = {
                oldPassword: oldPassword,
                newPassword: newPassword
            };

            if (userName) data.userName = userName;

            return ($http.post('/api/auth/changepassword', data));
        }

        function isAllowed(roles) {
            if (!_.isArray(roles)) roles = [roles];
            return _.intersection(roles, service.details.roles).length > 0;
        }

        function openPassChangeModal(passChangeRequired, userCreds) {
            return $uibModal.open({
                templateUrl: 'AppJs/advanced/user-profile/passChangeModal.html',
                backdrop: passChangeRequired ? 'static' : true,
                keyboard: !passChangeRequired,
                size: 'lg',
                controller: ['$scope', 'toastr', '$uibModalInstance', function ($scope, toastr, $uibModalInstance) {
                    angular.extend($scope, {
                        password: {},
                        submitIfReady: submitIfReady,
                        changePassword: changePassword,
                        isChangingPass: false,
                        allowCancel: !passChangeRequired,
                        isLongEnough: isLongEnough,
                        hasDigits: hasDigits,
                        hasLower: hasLower,
                        hasUpper: hasUpper,
                        hasSpecial: hasSpecial,
                        isVerified: isVerified,
                        hasError: false,
                        hideError: false
                    });

                    //$log.info("userCreds", userCreds);

                    if (userCreds)
                        $scope.password.oldPassword = userCreds.password;

                    function changePassword() {
                        $scope.isChangingPass = true;

                        //$log.info("Changing Password...", userCreds);
                        return service
                            .changePassword($scope.password.oldPassword, $scope.password.newPassword, userCreds ? userCreds.name : null)
                            .then(function (result) {

                                //$log.info("result", result);
                                $scope.isChangingPass = false;

                                if (result.data.isOk === true) {
                                    toastr.success("Your password has been changed.");
                                    $uibModalInstance.close(userCreds ? { name: userCreds.name, password: $scope.password.newPassword } : true);
                                }
                                else {
                                    toastr.error("We're not sure what happened, but when we tried to change your password an error occurred. Consider trying again.");
                                    $scope.hasError = true;
                                }
                            });
                    }

                    function submitIfReady(e, isValid) {
                        e.preventDefault();
                        if (isValid)
                            changePassword();
                    }

                    function isLongEnough(val) {
                        return val && val.length >= 12;
                    }

                    function hasDigits(val) {
                        return /\d/.test(val);
                    }

                    function hasLower(val) {
                        return /[a-z]/.test(val);
                    }

                    function hasUpper(val) {
                        return /[A-Z]/.test(val);
                    }

                    function hasSpecial(val) {
                        return /[@!$%#]{1,}/.test(val);
                    }

                    function isVerified(val, val2) {
                        return val == val2;
                    }
                }]
            }).result;
        }

    }
})();;
(function () {
	'use strict';

	angular
		.module('app')
		.controller('LoginController', LoginController);

	LoginController.$inject = ['config', '$state', '$stateParams', '$location', '$scope', '$rootScope', 'AuthService', 'Idle', '$timeout', '$log', 'UserData', 'Dialogger', 'COOKIE_KEYS', '$cookies'];

	function LoginController(config, $state, $stateParams, $location, $scope, $rootScope, Auth, Idle, $timeout, $log, UserData, Dialogger, COOKIE_KEYS, $cookies) {
		angular.extend($scope,
			{
				showError: false,
				showForm: config.authMethod == "Forms",
				user: { name: "", password: "" },
				loginSubmit: loginSubmit,
				loggingIn: false,
				loggedOut: !!$stateParams.loggedOut,
				useLoginGovRedirect: false
			});

		activate();

		function activate() {
			//if ($scope.loggedOut)
			//{
			//    logout();   // if the logged out flag is set, make sure that the actual logout method has been called
			//}

			if (Auth.isLoggedIn()) {

				idlize();

				//$log.info("Already logged in...")
				if ($rootScope.afterLoginState) {
					var state = $rootScope.afterLoginState.state,
						params = $rootScope.afterLoginState.params;
					delete $rootScope.afterLoginState;
					$state.go(state, params);
				} else {
					$state.go("root.adv.index");
				}

			}
			else if (config.authMethod != "WindowsIntegrated") {
				// login.gov after Dec 11, 2023 at 9am
				const loginGovEnableDate = new Date(2023, 11, 11, 9, 0);
				const curDate = new Date();
				if (curDate > loginGovEnableDate) {
					$scope.useLoginGovRedirect = false;
					window.location.replace("/logingov/");
				}
			} else if (config.authMethod == "WindowsIntegrated" && !$scope.loggedOut) {
				loginSubmit(); //auto login
			}
		}

		function logout() {
			// clear all user data and logout
			UserData.dataObject.reset();
			Auth.logout();
			$state.reload();
		}

		function loginSubmit(e) {
			if (e) e.preventDefault();

			$scope.loggingIn = true;

			var loginPromise = (config.authMethod == "Forms")
				? Auth.login($scope.user.name, $scope.user.password)
				: Auth.login();

			//$log.info("Logging in...");

			loginPromise.then(function (result) {
				if (result.isOk) {
					var isLoggedIn = Auth.isLoggedIn();
					var isPasswordExpired = result.isExpired;

					if (!isLoggedIn && !isPasswordExpired) {   // bad login attempt
						$scope.showError = true;
						$scope.loggingIn = false;
						$scope.isDisabled = result.isDisabled;
					}
					else {
						// last login notice
						var lastLoginNotice = '';
						if (result.lastLoginDate != undefined && Date.parse(result.lastLoginDate) != NaN) {
							lastLoginNotice = 'Last login: ' + result.lastLoginDate + '<br />';
						}
						if (result.failedLoginCount != undefined && result.failedLoginCount > 0) {
							lastLoginNotice = lastLoginNotice + 'Failed login attempts: ' + result.failedLoginCount + '<br />';
						}
						if (result.lastFailedLoginDate != undefined && Date.parse(result.lastFailedLoginDate) != NaN) {
							lastLoginNotice = lastLoginNotice + 'Last failed login attempt: ' + result.lastFailedLoginDate + '<br />';
						}

						if (lastLoginNotice == '') { lastLoginNotice = 'Welcome, this is your first time logging into CASSIDI.'; }

						var hasSeenLoginNoteCookie = $cookies.get(COOKIE_KEYS.LastLoginInfo);
						var hasSeenLastLoginNote = false;
						if (hasSeenLoginNoteCookie !== undefined && hasSeenLoginNoteCookie === '1') {
							hasSeenLastLoginNote = true;
						}

						if (!hasSeenLastLoginNote) {
							var lastLoginNoticeDialog = Dialogger.alert(lastLoginNotice);
							lastLoginNoticeDialog.then(function (confirmed) {
								doAfterAuthTasks(isLoggedIn)
								$cookies.put(COOKIE_KEYS.LastLoginInfo, '1');
							});
						}
						else {
							doAfterAuthTasks(isLoggedIn)
						}

						//var lastLoginNoticeDialog = Dialogger.confirm(lastLoginNotice);
						//lastLoginNoticeDialog.then(function (confirmed) {
						//	doAfterAuthTasks(isLoggedIn)

						//if (isLoggedIn) {
						//	idlize();

						//	$scope.user.name = "";
						//	$scope.user.password = "";

						//	if ($rootScope.afterLoginState) {
						//		var state = $rootScope.afterLoginState.state,
						//			params = $rootScope.afterLoginState.params;
						//		delete $rootScope.afterLoginState;
						//		$state.go(state, params);
						//	} else {
						//		$state.go("root.adv.index");
						//	}
						//} else {
						//	var userCreds = angular.extend({}, $scope.user);
						//	$scope.user.name = "";
						//	$scope.user.password = "";

						//	Auth
						//		.openPassChangeModal(true, userCreds) //true = passChangeRequired
						//		.then(function (result) {
						//			//$log.info("prelogin result", result);
						//			if (typeof result == "object" && result.name && result.password) {
						//				$timeout(function () {
						//					//$log.info("done!");
						//					$scope.user.name = result.name;
						//					$scope.user.password = result.password;
						//					loginSubmit();
						//				},
						//					500);
						//			}
						//		});
						//}


						//});
					}
				} else {
					$scope.loggingIn = false;
					alert("Access Denied. \n\nIf you have a business need to access the CASSIDI\xAE application please contact the CASSIDI Team at cassidi@stls.frb.org.");
					// Note: \xAE in message is hex value for reg trademark symbol
				}
			});
		}

		function doAfterAuthTasks(isLoggedInFlag) {
			if (isLoggedInFlag) {
				idlize();

				$scope.user.name = "";
				$scope.user.password = "";

				if ($rootScope.afterLoginState) {
					var state = $rootScope.afterLoginState.state,
						params = $rootScope.afterLoginState.params;
					delete $rootScope.afterLoginState;
					$state.go(state, params);
				} else {
					$state.go("root.adv.index");
				}
			} else {
				var userCreds = angular.extend({}, $scope.user);
				$scope.user.name = "";
				$scope.user.password = "";

				Auth
					.openPassChangeModal(true, userCreds) //true = passChangeRequired
					.then(function (result) {
						//$log.info("prelogin result", result);
						if (typeof result == "object" && result.name && result.password) {
							$timeout(function () {
								//$log.info("done!");
								$scope.user.name = result.name;
								$scope.user.password = result.password;
								loginSubmit();
							},
								500);
						}
					});
			}
		}

		function idlize() {

			if (!Idle.running())
				Idle.watch(); //Start paying attention to idleness

		}
	}
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('NotAllowedController', NotAllowedController);

    NotAllowedController.$inject = ['$scope', '$state', '$log', 'AuthService'];

    function NotAllowedController($scope, $state, $log, Auth) {
        $scope.logOutAndGoPublic = logOutAndGoPublic;
        $scope.firstName = Auth.details.first;

        activate();

        function activate() {
            if (Auth.isAuthorized()) {
                $log.warn("Authorized user at the Not-Allowed page is redirected to the advanced home page.");
                $state.go("root.adv.index");
            }
        }

        function logOutAndGoPublic() {
            Auth.logout()
                .then(function (isOk) {
                    $state.go("root.index");
                });
        }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .factory('Dialogger', Dialogger);

    Dialogger.$inject = ['$uibModal', '$log'];

    function Dialogger($uibModal, $log) {
        var modalDefaults = {
            backdrop: true,
            keyboard: true,
            modalFade: true,
            templateUrl: '/AppJs/common/dialogger/standard.html',
            windowClass: 'cassidi-standard-modal'
        };

        var modalOptions = {
            closeButtonText: 'Close',
            actionButtonText: 'OK',
            headerText: null,
            bodyText: 'No message.'
        };

        var service = {
            show: show,
            showModal: showModal,
            alert: showAlert,
            info: showInfo,
            confirm: showConfirmation,
            pickDate: showDatePicker,
            searchInstitutions: searchInstitutions
        };

        return service;
        ////////////////

        function showModal(customModalDefaults, customModalOptions) {
            if (!customModalDefaults) customModalDefaults = {};
            customModalDefaults.backdrop = 'static';
            return show(customModalDefaults, customModalOptions);
        }

        function show(customModalDefaults, customModalOptions) {
            //Create temp objects to work with since we're in a singleton service
            var tempModalDefaults = {};
            var tempModalOptions = {};

            if (customModalDefaults && customModalDefaults.isAlert)
                customModalDefaults.windowClass = 'cassidi-standard-modal alert';

            if (customModalDefaults && customModalDefaults.isAlert)
                customModalDefaults.windowClass = 'cassidi-standard-modal info';

            if (customModalDefaults && customModalDefaults.isConfirmation)
                customModalDefaults.windowClass = 'cassidi-standard-modal confirmation';

            if (customModalDefaults && customModalDefaults.isDatePicker)
                customModalDefaults.windowClass = 'cassidi-standard-modal date-picker';

            //Map angular-ui modal custom defaults to modal defaults defined in service
            angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);

            //Map modal.html $scope custom properties to defaults defined in service
            angular.extend(tempModalOptions, modalOptions, customModalOptions);

            if (!tempModalDefaults.controller) {
                tempModalDefaults.controller = ["$scope", "$uibModalInstance", function ($scope, $uibModalInstance) {
                    $scope.modalOptions = tempModalOptions;

                    //$log.info("modalOptions", $scope.modalOptions);

                    $scope.modalOptions.ok = function (result) {
                        if (customModalDefaults && customModalDefaults.isConfirmation)
                            $uibModalInstance.close(true);
                        else
                            $uibModalInstance.close(result);
                    };
                    $scope.modalOptions.close = function () {
                        if (customModalDefaults && customModalDefaults.isConfirmation)
                            $uibModalInstance.close(false);
                        else
                            $uibModalInstance.dismiss('cancel');
                    };

                    $scope.modalOptions.showHeader = function () {
                        return !!$scope.modalOptions.headerText;
                    };

                    $scope.modalOptions.showCloseButton = function () {
                        return !!$scope.modalOptions.closeButtonText;
                    }
                }];
            }

            return $uibModal.open(tempModalDefaults).result;
        }

        function showAlert(message, title) {
            var options = {
                bodyText: message,
                closeButtonText: null,
            };
            if (title) options.headerText = title;

            return showModal({ isAlert: true }, options);
        }

        function showInfo(message, title) {
            var options = {
                bodyText: message,
                closeButtonText: null,
            };
            if (title) options.headerText = title;

            return showModal({ isInfo: true }, options);
        }

        function showConfirmation(message, title, yesNo) {
            var options = {
                bodyText: message,
                closeButtonText: 'Cancel',
            };
            if (title) options.headerText = title;
            if (yesNo === true) {
                options.actionButtonText = 'Yes';
                options.closeButtonText = 'No';
            }

            return showModal({ isConfirmation: true }, options);
        }

        function showDatePicker(prompt, selectedDate, dpOptions) {
            var options = {
                headerText: prompt,
                dpVal: selectedDate,
                dpOptions: dpOptions || {
                    minDate: new Date(),
                    showWeeks: true
                }
            }

            var defaults = {
                isDatePicker: true,
                templateUrl: '/AppJs/common/dialogger/datePicker.html',
                size: 'sm'
            };

            return showModal(defaults, options);
        }

        function searchInstitutions(allowMultiSelect) {
            var modalSettings = {
                backdrop: true,
                keyboard: true,
                modalFade: true,
                windowClass: 'cassidi-standard-modal',
                templateUrl: '/AppJs/common/dialogger/searchInstitutions.html',
                size: 'lg',
                controller: ["$scope", "$uibModalInstance", function ($scope, $uibModalInstance) {
                    angular.extend($scope, {
                        results: [],
                        save: function ($close) {
                            console.log("options.save!");
                            $close(this.results);
                        },
                        searchByRssdOrFdic: function (criteria) {
                            this.results = [1, 2, 3, 4, 5]; //go get results based on criteria
                            console.log("searchByRssdOrFdic", this.results);
                            $scope.isResultsTabActive = true;
                        },
                        searchByArea: function (criteria) {
                            this.results = [999, 888, 777, 666]; //go get results based on criteria
                            console.log("searchByArea", this.results);
                            $scope.isResultsTabActive = true;
                        },
                        goToResultsTab: function () {
                            $scope.isResultsTabActive = true;
                        }
                    });
                }]
            };

            return $uibModal.open(modalSettings).result;
        }
    }
})();;
(function () {
    angular.module('app')
           .directive('branchMultiPicker', branchMultiPicker);

    branchMultiPicker.$inject = ['$log'];

    function branchMultiPicker($log) {
        // Usage:
        //     <branch-multi-picker ng-model="bindToVariable"></branch-picker>
        //      - ng-model      REQUIRED        the variable to bind to
        //      - id            OPTIONAL        the id of the resulting element
        //                                      NOTE: the internal inbput box will have id appended with "_input" 
        //                                            the dropdown button will have id appended with "_button"
        //      - class         OPTIONAL        class name to apply to outer wrapper of resulting element
        //      - left-right    OPTIONAL        controls how dropdown is aligned, left to left side button or right to right side of button (defaults to "right")
        //
        // Creates:
        //     textbox with RSSD picker dropdown button
        var directive = {
            restrict: 'E',
            replace: true,
            scope: {
                model: '=ngModel',
                id: '@',
                className: '@class',
                leftRight: '@',
                blur: '&pickerBlur',
                name: "@",
                returnType: "@", // rssdId, branchId, cassidiId, facility, firmat, uninumber
                callBack: '@',
                disabled: '=',
                instList: '='
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            controller: ['$scope', 'UserData', function ($scope, UserData) {

                $scope.checkModel = [];

                if ($scope.instList == null)
                    $scope.instList = UserData.institutions.get();

                $scope.id = $scope.id + "branch-picker-" + new Date().getTime();
                $scope.UserData = UserData;

                $scope.pickOne = function (branch) {

                    $scope.model = $scope.getTypeValue(branch);

                };

                $scope.getTypeValue = function(branch) {

                    switch ($scope.returnType) {
                        case "rssdId":
                            {
                                return branch.rssdId;
                            }
                        case "branchId":
                            {
                                return branch.branchId;
                            }
                        case "cassidiId":
                            {
                                return branch.cassidiId;
                            }
                        case "facility":
                            {
                                return branch.facility;
                            }
                        case "firmat":
                            {
                                return branch.firmat;
                            }
                        case "uninumber":
                            {
                                return branch.uninumber;
                            }
                    }

                    return branch.branchId;
                };

                $scope.isChecked = function (branch) {
                    return _.includes($scope.checkModel, branch);
                };


                $scope.selectCheck = function (branch, $event) {

                    if ($scope.isChecked(branch)) {
                        _.remove($scope.checkModel, function (n) {
                            return n == branch;
                        });
                    } else {
                        $scope.checkModel.push(branch);
                    }

                    $event.stopPropagation();
                    $event.target.blur();

                    return false;
                };

                $scope.commitChanges = function () {
                    $scope.model = _.join(_.map($scope.checkModel, function (e) { return $scope.getTypeValue(e); }), [separator = ', ']);
                    $scope.callFn({ 'targets': $scope.model });

                    $scope.checkModel = [];
                };


                $scope.$watch('instList', function (newValue, oldValue) {

                    $scope.rebuildList();

                });

                $scope.rebuildList = function() {

                    $scope.containingInsts = [];

                    _.each($scope.instList,
                        function (inst) {
                            if (inst) {
                                if (inst.definition)
                                    inst.name = inst.definition.name;

                                if (inst.branches.length > 0)
                                    $scope.containingInsts.push(inst);

                                _.each(inst.orgs,
                                    function(org) {
                                        if (org.branches.length > 0)
                                            $scope.containingInsts.push(org);
                                    });
                            }
                        });
                };

                $scope.leftRightClass = $scope.leftRight == "left" ? "dropdown-menu-left" : "dropdown-menu-right";
                $scope.rebuildList();
            }],
            templateUrl: '/AppJs/common/directives/branchMultiPicker.html'
        };
        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('branchPicker', branchPicker);

    branchPicker.$inject = ['$log'];

    function branchPicker($log) {
        // Usage:
        //     <branch-picker ng-model="bindToVariable"></branch-picker>
        //      - ng-model      REQUIRED        the variable to bind to
        //      - id            OPTIONAL        the id of the resulting element
        //                                      NOTE: the internal inbput box will have id appended with "_input" 
        //                                            the dropdown button will have id appended with "_button"
        //      - class         OPTIONAL        class name to apply to outer wrapper of resulting element
        //      - left-right    OPTIONAL        controls how dropdown is aligned, left to left side button or right to right side of button (defaults to "right")
        //
        // Creates:
        //     textbox with RSSD picker dropdown button
        var directive = {
            restrict: 'E',
            replace: true,
            scope: {
                model: '=ngModel',
                id: '@',
                className: '@class',
                leftRight: '@',
                blur: '&pickerBlur',
                name: "@",
                returnType: "@", // rssdId, branchId, cassidiId, facility, firmat, uninumber
                callBack: '@',
                instList: '='
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            link: function (scope, el, attrs) {
                el.bind("keyup", function (code) {
                    if (code.keyCode == 13) {
                        if (scope.callBack != undefined) {
                            scope.$apply();
                            $("#" + scope.callBack).click();
                        }
                    }
                });
                // If the input control is changed to a new child location below in the template this el[0].children[X] needs to be updated.
                if (attrs.hasFocus != undefined && attrs.hasFocus == "yes")
                    document.getElementById(el[0].children[0].id).focus();
            },
            controller: ['$scope', 'UserData', function ($scope, UserData) {

                if ($scope.instList == null)
                    $scope.instList = UserData.institutions.get();

                $scope.id = $scope.id + "branch-picker-" + new Date().getTime();
                $scope.UserData = UserData;

                $scope.pickOne = function (branch) {

                    $scope.model = $scope.getTypeValue(branch);

                };

                $scope.getTypeValue = function(branch) {

                    switch ($scope.returnType) {
                        case "rssdId":
                            {
                                return branch.rssdId;
                            }
                        case "branchId":
                            {
                                return branch.branchId;
                            }
                        case "cassidiId":
                            {
                                return branch.cassidiId;
                            }
                        case "facility":
                            {
                                return branch.facility;
                            }
                        case "firmat":
                            {
                                return branch.firmat;
                            }
                        case "uninumber":
                            {
                                return branch.uninumber;
                            }
                    }

                    return branch.branchId;
                };

                $scope.leftRightClass = $scope.leftRight == "left" ? "dropdown-menu-left" : "dropdown-menu-right";

                $scope.containingInsts = [];


                _.each($scope.instList,
                    function (inst) {
                        if (inst.branches.length > 0)
                            $scope.containingInsts.push(inst);

                        _.each(inst.orgs,
                           function (org) {
                               if (org.branches.length > 0)
                                    $scope.containingInsts.push(org);
                           });
                    });
            }],
            template: '\
<div id="{{id}}" class="input-group {{className}}">\
    <input id="{{id}}_input" type="text" class="form-control" name="{{name}}" aria-label="select from saved branches" ng-model="model" ng-pattern="/^[0-9]{1,15}$/"  ng-blur="blur($event)" />\
    <div class="input-group-btn" uib-dropdown>\
        <button id="{{id}}_button" type="button" class="btn btn-default"  uib-dropdown-toggle ng-disabled="containingInsts.length > 0">\
            <i class="fa fa-list-ul"></i> <span class="caret"></span>\
        </button>\
        <ul class="dropdown-menu {{leftRightClass}}" uib-dropdown-menu role="menu" aria-labelledby="{{id}}_button">\
            <li ng-repeat-start="inst in containingInsts"><strong>{{inst.name}}</strong></li>\
            <li ng-repeat-end ng-repeat="branch in inst.branches"><a ng-click="pickOne(branch)"><strong>{{getTypeValue(branch)}}</strong> - <i>{{branch.city}},{{branch.state}} {{branch.address.length>20 ? branch.address.substr(0,18)+"&hellip;" : branch.address}}</i></a></li>\
        </span>\
    </div>\
</div>'
        };
        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('branchViewer', branchViewer);

    branchViewer.$inject = ['$interpolate', '$state', 'AdvBranchesService'];

    function branchViewer($interpolate, $state, AdvBranchesService) {
        // Usage:
        // 
        // Creates:
        // 

        //var directive = {
        //    restrict: 'E',
        //    replace: true,
        //    templateUrl: '/AppJS/common/directives/branchViewer.html',
        //    controller: ['$scope', '$state', function ($scope, $state) {

        //        $scope.stateStack = [];

        //        var state = $state.current;
        //        do {

        //        } while (true);
        //    }]
        //};


        var directive = {
            restrict: 'E',
            templateUrl: '/AppJS/common/directives/branchViewer.html',
            scope: {
                inst: '=',
                criteria: '='
            },
            link: function (scope) {


                scope.branchToggleInst = function (open, inst) {

                    if (open) {
                        scope.updateBranchListInst(inst);
                    }

                };


                scope.rebuildList = function (seller, instList) {

                    seller.branchList = [];

                    _.each(instList,
                        function (inst) {
                            if (inst && inst.branches) {

                                if (inst.branches.length > 0)
                                    seller.branchList = seller.branchList.concat(inst.branches);

                                _.each(inst.orgs,
                                    function (org) {
                                        if (org.branches.length > 0)
                                            seller.branchList = seller.branchList.concat(org.branches);
                                    });
                            }
                        });

                };


                scope.updateBranchListInst = function (inst) {

                    var rssdId = inst.rssdid ? inst.rssdid : inst.rssdId;

                    if (scope.criteria.regionType == 'bankingMarket' && scope.criteria.marketID) {

                        if (inst.lastRun == rssdId + "marketID" + scope.criteria.marketID) {
                            return;
                        }

                        inst.isLoading = true;

                        AdvBranchesService.getBranchSearchData({ parentRssdId: rssdId, marketNumber: Number(scope.criteria.marketID), entityType: scope.inst.entityType }).then(function (result) {
                            inst.lastRun = rssdId + "marketID" + scope.criteria.marketID;
                            scope.rebuildList(inst, result);
                            inst.isLoading = false;
                        });
                    } else if (scope.criteria.regionType == 'msa' && scope.criteria.msa != null) {

                        if (inst.lastRun == rssdId + "msa" + scope.criteria.msa.msaId) {
                            return;
                        }

                        inst.isLoading = true;

                        AdvBranchesService.getBranchSearchData({ parentRssdId: rssdId, msa: scope.criteria.msa.msaId }).then(function (result) {
                            inst.lastRun = rssdId + "msa" + scope.criteria.msa.msaId;
                            scope.rebuildList(inst, result);
                            inst.isLoading = false;
                        });

                    } else if (scope.criteria.regionType == 'state' && scope.criteria.state != null) {

                        if (inst.lastRun == rssdId + "state" + scope.criteria.state.fipsId) {
                            return;
                        }

                        inst.isLoading = true;

                        AdvBranchesService.getBranchSearchData({ parentRssdId: rssdId, state: scope.criteria.state.fipsId }).then(function (result) {
                            inst.lastRun = rssdId + "msa" + scope.criteria.state.fipsId;
                            scope.rebuildList(inst, result);
                            inst.isLoading = false;
                        });

                    } else if (scope.criteria.regionType == 'customMarket' && scope.criteria.customMarket != null) {

                        if (inst.lastRun == rssdId + "customMarketID" + scope.criteria.customMarket.customMarketId) {
                            return;
                        }

                        inst.isLoading = true;

                        AdvBranchesService.getBranchSearchData({ parentRssdId: rssdId, customMarket: scope.criteria.customMarket.customMarketId }).then(function (result) {
                            inst.lastRun = rssdId + "customMarketID" + scope.criteria.customMarket.customMarketId;
                            scope.rebuildList(inst, result);
                            inst.isLoading = false;
                        });
                    }
                };
            }
        };

        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('breadCrumb', breadCrumb);

    breadCrumb.$inject = ['$interpolate', '$state'];

    function breadCrumb($interpolate, $state) {
        // Usage:
        // 
        // Creates:
        // 

        //var directive = {
        //    restrict: 'E',
        //    replace: true,
        //    templateUrl: '/AppJS/common/directives/breadCrumb.html',
        //    controller: ['$scope', '$state', function ($scope, $state) {

        //        $scope.stateStack = [];

        //        var state = $state.current;
        //        do {

        //        } while (true);
        //    }]
        //};

        var templateUrl = '/AppJS/common/directives/breadCrumb.html';

        var directive = {
            restrict: 'E',
            templateUrl: function (elem, attrs) {
                return attrs.templateUrl || templateUrl;
            },
            scope: {
                displaynameProperty: '@',
                abstractProxyProperty: '@?'
            },
            link: function (scope) {
                scope.breadcrumbs = [];
                scope.breadcrumbs.isAdvanced = false;
                if ($state.$current.name !== '') {
                    updateBreadcrumbsArray();
                }
                scope.$on('$stateChangeSuccess', function () {
                    updateBreadcrumbsArray();
                });

                /**
                 * Start with the current state and traverse up the path to build the
                 * array of breadcrumbs that can be used in an ng-repeat in the template.
                 */
                function updateBreadcrumbsArray() {
                    var workingState;
                    var displayName;
                    var breadcrumbs = [];
                    breadcrumbs.isAdvanced = false;
                    var currentState = $state.$current;

                    while (currentState && currentState.name !== '') {
                        workingState = getWorkingState(currentState);
                        if (workingState) {
                            displayName = getDisplayName(workingState);

                            if (displayName !== false && !stateAlreadyInBreadcrumbs(workingState, breadcrumbs)) {
                                breadcrumbs.push({
                                    displayName: displayName,
                                    route: workingState.name,
                                    //abstract: workingState.abstract
                                });

                                if (workingState.name.toLowerCase().indexOf('.adv') > -1) { breadcrumbs.isAdvanced = true;}
                            }
                        }
                        currentState = currentState.parent;
                    }
                    breadcrumbs.reverse();
                    scope.breadcrumbs = breadcrumbs;
                }

                /**
                 * Get the state to put in the breadcrumbs array, taking into account that if the current state is abstract,
                 * we need to either substitute it with the state named in the `scope.abstractProxyProperty` property, or
                 * set it to `false` which means this breadcrumb level will be skipped entirely.
                 * @param currentState
                 * @returns {*}
                 */
                function getWorkingState(currentState) {
                    var proxyStateName;
                    var workingState = currentState;
                    if (currentState.abstract === true) {
                        /*if (currentState.data.abstractOverride === true) {
                            //leave as is
                        } else
                        */
                        if (typeof scope.abstractProxyProperty !== 'undefined') {
                            proxyStateName = getObjectValue(scope.abstractProxyProperty, currentState);
                            if (proxyStateName) {
                                workingState = $state.get(proxyStateName);
                            } else {
                                workingState = false;
                            }
                        } else {
                            workingState = false;
                        }
                    }
                    return workingState;
                }

                /**
                 * Resolve the displayName of the specified state. Take the property specified by the `displayname-property`
                 * attribute and look up the corresponding property on the state's config object. The specified string can be interpolated against any resolved
                 * properties on the state config object, by using the usual {{ }} syntax.
                 * @param currentState
                 * @returns {*}
                 */
                function getDisplayName(currentState) {
                    var interpolationContext;
                    var propertyReference;
                    var displayName;

                    if (!scope.displaynameProperty) {
                        // if the displayname-property attribute was not specified, default to the state's name
                        return currentState.name;
                    }
                    propertyReference = getObjectValue(scope.displaynameProperty, currentState);

                    if (propertyReference === false) {
                        return false;
                    } else if (typeof propertyReference === 'undefined') {
                        return currentState.name;
                    } else {
                        // use the $interpolate service to handle any bindings in the propertyReference string.
                        interpolationContext = (typeof currentState.locals !== 'undefined') ? currentState.locals.globals : currentState;
                        displayName = $interpolate(propertyReference)(interpolationContext);
                        return displayName;
                    }
                }

                /**
                 * Given a string of the type 'object.property.property', traverse the given context (eg the current $state object) and return the
                 * value found at that path.
                 *
                 * @param objectPath
                 * @param context
                 * @returns {*}
                 */
                function getObjectValue(objectPath, context) {
                    var i;
                    var propertyArray = objectPath.split('.');
                    var propertyReference = context;

                    for (i = 0; i < propertyArray.length; i++) {
                        if (angular.isDefined(propertyReference[propertyArray[i]])) {
                            propertyReference = propertyReference[propertyArray[i]];
                        } else {
                            // if the specified property was not found, default to the state's name
                            return undefined;
                        }
                    }
                    return propertyReference;
                }

                /**
                 * Check whether the current `state` has already appeared in the current breadcrumbs array. This check is necessary
                 * when using abstract states that might specify a proxy that is already there in the breadcrumbs.
                 * @param state
                 * @param breadcrumbs
                 * @returns {boolean}
                 */
                function stateAlreadyInBreadcrumbs(state, breadcrumbs) {
                    var i;
                    var alreadyUsed = false;
                    for (i = 0; i < breadcrumbs.length; i++) {
                        if (breadcrumbs[i].route === state.name) {
                            alreadyUsed = true;
                        }
                    }
                    return alreadyUsed;
                }
            }
        };

        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('cassidiRole', cassidiRole);

    cassidiRole.$inject = ['AuthService', '$parse', '$rootScope'];

    function cassidiRole(Auth, $parse, $rootScope) {
        // Usage:
        //          <ANY cassidi-role="role-name-1[,role-name-2[,...]]" />
        // 
        // Creates:
        //          Hides an element if it cannot be used due to user not belonging to needed role
        // 
        var directive = {
            restrict: 'A',
            scope: {
                'cassidiRole': '@'
            },
            link: function link(scope, element, attrs) {
                var allowedRoles =
                    _.map(_.split(scope.cassidiRole, /[|,]+/g), function (s) {
                        return _.startsWith(s, "ROLES.") ? $parse(s)($rootScope) : s;
                    });

                if (!Auth.isAllowed(allowedRoles)) {
                    //element.css('background-color', 'pink');
                    element.hide();
                //} else {
                //    element.css('outline', '1px lime solid');
                }
            }
        };
        return directive;


    };
})();;
(function () {
	angular.module('app')
		.directive('changePacketPicker', changePacketPicker);

	changePacketPicker.$inject = ['$log'];

	function changePacketPicker() {
 
		var directive = {
			restrict: 'E',
			replace: true,
			templateUrl: '/AppJs/common/directives/changePacketPicker.html',
			scope: {
				model: '=ngModel',
				id: '@',
				className: '@class',				
				name: "@",
				rssdid: '@',
				callBack: '@'

			},
			controller: ['$scope', 'AdvInstitutionsService', '$uibModal', '$attrs', function ($scope, AdvInstitutionsService, $uibModal, $attrs) {
				//if (typeof ($scope.rssdId) != 'number') { $scope.rssdId = -1; }
				$scope.openPackets = [];
				$scope.showPacket = false;
				$scope.selectedPacket = [];
				$scope.packetTitle = formatChangePacketLabel();
				$scope.togglePacketList = togglePacketList;
				$scope.formatHistoryCodeName = formatHistoryCodeName;
				$scope.formatChangePacketLabel = formatChangePacketLabel;
				$scope.linkChangePacket = linkChangePacket;
				$scope.hideLabel = false;

				activate();

				function activate() {
					if ($attrs.hideLabel != undefined && $attrs.hideLabel == "1") { $scope.hideLabel = true; }
					$scope.openPackets = getUnlinkedPackets();
					$scope.formatChangePacketLabel();
				}

				function getUnlinkedPackets() {
					AdvInstitutionsService.getUnlinkedChangePackets($scope.rssdid).then(function (result) {
						$scope.openPackets = result.data;
					});
				}

				function togglePacketList(isCurrentlyOpen) {					
					if (isCurrentlyOpen === true) {
						$scope.showPacket = false;
					}
					else if (isCurrentlyOpen === false) {
						$scope.showPacket = true;
					}
					else {
						$scope.showPacket = !$scope.showPacket;
					}
				}

				function setSelectedPacketId(packetId) {
					$scope.ngModel = packetId;

				}

				function formatHistoryCodeName(histCodeName) {
					return histCodeName != null ? histCodeName.replace(/_/g, ' ') : '';
				}

				function linkChangePacket(packet) {					
					$scope.model = packet.id;
					$scope.selectedPacket = packet;
					$scope.packetTitle = $scope.formatChangePacketLabel();
					$scope.togglePacketList(); // close the picker

					//copy working path to clipboard
					var workingPath = $scope.selectedPacket.workingPath;
					var dt = new Date();
					var filename = "2_historydoc_" + dt.getTime() + ".pdf";

					var packetPathHolder = document.getElementById("packetPathHolder");
					packetPathHolder.value = workingPath + '\\' + filename;

					/* Select the text field */
					packetPathHolder.select();
					packetPathHolder.setSelectionRange(0, 99999); /*For mobile devices*/

					/* Copy the text inside the text field */
					document.execCommand("copy");
				}

				function copyWorkingPathToClipboard() {
					var workingPath = $scope.selectedPacket.workingPath;
					var dt = new Date();
					var filename = "2_historydoc_" + dt.getTime() + ".pdf";
					//var txtbox = document.createElement('textarea');
					txtbox = document.getElementById("clipboardCopyHolder");
					txtbox.value = workingPath + '\\' + filename;
					//document.body.appendChild(txtbox);
					txtbox.select();
					document.execCommand('copy');
					//document.body.removeChild(txtbox);
				}

				function formatChangePacketLabel() {
					if (!$scope.selectedPacket || !$scope.selectedPacket.id || $scope.selectedPacket.id < 0) {
						return "-- select a change packet --";
					}
					else {
						return $scope.selectedPacket.rssdId + ": " + $scope.selectedPacket.title + " (" + $scope.selectedPacket.adminUserId + ")";
					}
				}

				
			}]
		};
		return directive;
	};
})();;
(function () {
    angular.module('app')
           .directive('countyPicker', countyPicker);

    countyPicker.$inject = [];

    function countyPicker() {
        // Usage:
        //          <county-picker county="countyObject" />
        // 
        // Creates:
        //          A button for selecting the county of a state
        // 
        var directive = {
            restrict: 'E',
            replace: true,
            templateUrl: '/AppJs/common/directives/countyPicker.html',
            scope: {
                county: '='
            },
            controller: ['$scope', function ($scope) {
            }]
        };
        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('datePicker', datePicker);

    datePicker.$inject = ['$log', 'toastr', 'UtilityService', '$timeout'];

    function datePicker($log, toastr, UtilityService, $timeout) {
        // Usage:
        //     <date-picker id="yourId" ng-model="bindToVariable" class="optional-class-name" date-format="MM/dd/yyyy"></date-picker>
        //      - ng-model      REQUIRED        the variable to bind to. must be a JavaScript date OR null
        //      - id            OPTIONAL        the id of the resulting element
        //                                      NOTE: the internal inbput box will have id appended with "_input" 
        //                                            the dropdown button will have id appended with "_button"
        //      - class         OPTIONAL        class name to apply to outer wrapper of resulting element
        //      - date-format   OPTIONAL        format of the date as it should appear in the textbox (defaults to MM/dd/yyyy)
        //      - setfocus      OPTIONAL        specifies if the date input field should automatically be given focus at init 
        //                                      (hasfocus="true", hasfocus="false", defaults to false)
        //
        // Creates:
        //     textbox with datepicker dropdown button
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            scope: {
                model: '=ngModel',
                dateFormat: '@',
                id: '@',
                className: '@class',
                equalLess: '@',
                setfocus: '@'
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            controller: ['uibDateParser', function (uibDateParser) {
                // we inject uibDateParser to format the date. no add'l action needed
            }],
            templateUrl: 'AppJs/common/directives/datePicker.html'
        };
        return directive;

        $scope.isCalendarOpened = false;

        function setfocus(dtPickerId) {
            var domInputField = document.getElementById(dtPickerId + "_input");
            if (domInputField) { domInputField.focus(); }
        }

        function link(scope, element, attrs) {
            scope.dateFormat = scope.dateFormat || "MM/dd/yyyy";
            scope.id = scope.id || "cass-dp_" + new Date().getTime();          

            scope.parseDate = function () {
                var textbox = document.getElementById(scope.id + "_input");
                var text = textbox.value; // document.getElementById(scope.id + "_input").value
                var dates = [];
                var pickerDate ;
                var match = false;
                var tp = scope.model;

                if (_.indexOf(text, "-") > -1) {
                    dates = text.split("-");
                    match = true;

                    if (dates[0].length == 4) {
                        pickerDate = minTwoDigits(dates[1]) + "/" + minTwoDigits(dates[2]) + "/" + dates[0];
                        scope.model = pickerDate;
                    }
                    else {
                        pickerDate = minTwoDigits(dates[0]) + "/" + minTwoDigits(dates[1]) + "/" +  minFourDigitsYear(dates[2]);
                        scope.model = pickerDate;
                    }
                       
                }
                if (!match) {
                    if (_.indexOf(text, "/") > -1) {
                        dates = text.split("/");
                        pickerDate = minTwoDigits(dates[0]) + "/" + minTwoDigits(dates[1]) + "/" + minFourDigitsYear(dates[2]);
                        scope.model = pickerDate;

                    }
                }
                if (!scope.model == "") {

                    //if (new Date(scope.model) == "Invalid Date") {
                    //    toastr.error("Date " + scope.model + ", is not a valid Date Format, please try again.");
                    //    scope.model = "";
                    //}
                    var data = {
                        dateString: scope.model
                    };
                    UtilityService
                     .IsDateString(data)
                     .then(function (result) {
                         if (!result.isDate) {
                             toastr.error("Date " + scope.model + ", is not a valid Date, please try again.");
                             scope.model = "";
                         }
                         else {
                             if (scope.equalLess) {
                                 var d = new Date();
                                 var transdate = new Date(scope.model);
                                 if (d <= transdate) {
                                     toastr.error("Date must be Current or Previous date.");
                                     scope.model = "";
                                 }
                             }
                         }
                     });

                }

                  
            };
            function minTwoDigits(n) {
                return (n < 10 && n.length == 1 ? '0' : '') + n;
            }
            function minFourDigitsYear(n) {
                if (n.length == 2)
                    n = (n > 50) ? '19' + n : '20' + n;

                return n;
            }

            if (scope.setfocus && scope.setfocus.length > 0 && scope.setfocus.toLowerCase() != 'false')
            {
                $timeout(function () { setfocus(scope.id); }, 100);
            }
        }
    };
})();
;
(function () {
    angular.module('app')
           .directive('exportToPdf', exportToPdf);

    exportToPdf.$inject = ['$state', '$stateParams', '$rootScope', '$log'];

    function exportToPdf($state, $stateParams, $rootScope, $log) {
        // Usage:
        //          <export-to-pdf />
        // Creates:
        //          An anchor-based button a user can click to open the PDF version of the viewed page.
        //          Login in this diretive determines what views this button will appear for and also
        //          extracts the appropriate parameters to pass to the report controller's action.

        var directive = {
            restrict: 'E',
            replace: true,
            template: '<a ng-if="showExportLink" target="_blank" class="btn btn-xs btn-default" ng-href="/report/{{reportAction}}?{{params}}"><i class="fa fa-file-pdf-o"></i> Export to PDF</a>',
            controller: ["$scope", function ($scope) {
                $rootScope.$on("$stateChangeSuccess",
                    function (event, toState, toParams, fromState, fromParams) {
                        setScope($scope, toState, toParams);
                    });

                // Initialize scope parameters
                setScope($scope, $state.current, $stateParams, $rootScope);
            }]
        };
        return directive;

        function setScope(scope, state, params, rootScope) {

            switch (state.name) {
                case "root.institutions.list":
                    scope.showExportLink = true;
                    scope.reportAction = "institutionlist";
                    scope.params = getParamsAsString(params, "name", "state|stateId", "county|countyId", "city|cityId", "zip");
                    break;

                case "root.institutions.summary.orgs":
                    scope.showExportLink = true;
                    scope.reportAction = "institutionsubs";
                    scope.params = getParamsAsString(params, ["rssdId", $state.params.rssd], "state|stateId", "county|countyId", "city|cityId", "zip");
                    break;

                case "root.institutions.summary.markets":
                    scope.showExportLink = true;
                    scope.reportAction = "institutionmarkets";
                    scope.params = getParamsAsString(params, ["rssdId", $state.params.rssd], "state|stateId", "county|countyId", "city|cityId", "zip");
                    break;

                case "root.markets.list":
                    scope.showExportLink = true;
                    scope.reportAction = "marketlist";
                    scope.params = getParamsAsString(params, "state|stateId", "county|countyId", "city|cityId", "zip");
                    break;

                case "root.markets.detail.definition":
                    scope.showExportLink = true;
                    scope.reportAction = "marketdefinition";
                    scope.params = getParamsAsString(params, ["marketId", $state.params.market], "state|stateId", "county|countyId", "city|cityId", "zip");
                    break;

                case "root.markets.detail.hhi":
                    scope.showExportLink = true;
                    scope.reportAction = "markethhi";
                    scope.params = getParamsAsString(params, ["marketId", $state.params.market], "state|stateId", "county|countyId", "city|cityId", "zip");
                    break;
                case "root.analysis.common-markets":
                    scope.showExportLink = true;
                    scope.reportAction = "CommonMarketsReport";
                    scope.params = getParamsAsString(params, "buyer|buyer", "targets|targets", "branches|branches");
                    break;
                //case "root.markets.detail.history":
                //    scope.showExportLink = true;
                //    scope.reportAction = "MarketHistoryPDF";
                //    scope.params = getParamsAsString(params, "market|marketId", ["filter", rootScope.filter]);
                //    break;
                default:
                    scope.showExportLink = false;
            }
        }

        function getParamsAsString() {
            var params = arguments[0],
                arr = [];

            for (var i = 1; i < arguments.length; i++) {
                if (_.isArray(arguments[i])) {
                    arr.push(arguments[i][0] + "=" + arguments[i][1]);
                } else {
                    var origArg = arguments[i];
                    var newArg = origArg;
                    if (origArg.indexOf("|") > -1) {
                        var args = origArg.split("|");
                        origArg = args[0];
                        newArg = args[1];
                    }

                    if (typeof params[origArg] != "undefined" && params[origArg] != null)
                        arr.push(newArg + "=" + params[origArg]);
                }
            }
            var result = _.join(arr, "&");
            return result;
        }
    };
})();;

(function () {
    angular.module('app')
           .directive('fedDistrict', fedDistrict);

    fedDistrict.$inject = ['$log', '$timeout'];

    function fedDistrict($log, $timeout) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            transclude: true,
            scope: {
                district: "=ngModel",
                outsideUs: "=",
                all: "=",
                bog: "=",
                change: "&?"
            },
            templateUrl: '/AppJs/common/directives/fedDistrict.html'
        };
        return directive;

        function link(scope, element, attrs) {
            scope.required = attrs.required === true;
            scope.name = attrs.name;
            scope.size = 'btn-group-sm'; //default
            scope.isOutsideUs = !!scope.outsideUs;
            scope.isAll = !!scope.all;
            scope.isBOG = !!scope.bog;
            var size = attrs.size;
            if (size == 'lg' || size == 'sm' || size == "xs")
                scope.size = 'btn-group-' + size;
            else if (size == 'md')
                scope.size = null;

            scope.clickDistrict = function (districtNo) {
                $log.info("clickDistrict", districtNo);
                scope.district = districtNo;

                if (scope.change)
                    $timeout(function () { scope.change(); }, 10);
            };
        }
    };
})();
;
(function () {
    angular.module("app")
           .directive("glossaryTerm", glossaryTerm);

    glossaryTerm.$inject = ["$log", "GlossaryService"];

    function glossaryTerm($log, Glossary) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: "E",
            replace: true,
            transclude: true,
            template: "<span ng-class='{\"gloss-term\": gotDef, \"is-icon\": isIcon}' uib-popover='{{definition}}' popover-title='{{title}}' popover-trigger='mouseenter' popover-class='wider' popover-placement='{{position}}' ng-transclude></span>",
            scope: {
                term: "@",
                isIcon: "=",
                position: "@?"
            }
        };
        return directive;

        function link(scope, element, attrs, ctrls, transclude) {
            scope.gotDef = false;
            scope.position = scope.position || "top";

            var term = scope.term
                ? scope.term
                : element.text();

            Glossary.getDef(term)
                .then(function (def) {
                    scope.gotDef = !!def;
                    scope.definition = def;
                    scope.title = term.toUpperCase();
                });
        }
    };
})();
;
(function () {
    angular.module('app')
        .directive('marketMultiPicker', marketMultiPicker);

    marketMultiPicker.$inject = ['$log'];

    function marketMultiPicker($log) {
        // Usage:
        //     <market-multi-picker ng-model="bindToVariable"></market-multi-picker>
        //      - ng-model      REQUIRED        the variable to bind to
        //      - id            OPTIONAL        the id of the resulting element
        //                                      NOTE: the internal inbput box will have id appended with "_input" 
        //                                            the dropdown button will have id appended with "_button"
        //      - class         OPTIONAL        class name to apply to outer wrapper of resulting element
        //      - left-right    OPTIONAL        controls how dropdown is aligned, left to left side button or right to right side of button (defaults to "right")
        //
        // Creates:
        //     textbox with market dropdown button
        var directive = {
            restrict: 'E',
            replace: true,
            scope: {
                model: '=ngModel',
                id: '@',
                className: '@class',
                leftRight: '@',
				callBack: '@',
				marketPickerCtr: '='
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            link: function(scope, el, attrs)
            {
				scope.myMarketPickerCtr = scope.marketPickerCtr || {};
				scope.myMarketPickerCtr.clearAllChecks = function () {
					scope.checkModel = [];
				}

				el.bind("keyup", function (code) {
                    if (code.keyCode == 13) {
                        if (scope.callBack != undefined) {
                            scope.$apply();
                            $("#" + scope.callBack).click();
                        }
                    }
                    });
            },
            controller: ['$scope', 'UserData', function ($scope, UserData) {

                $scope.checkModel = [];
                $scope.id = $scope.id || "mktno-picker-" + new Date().getTime();
                $scope.UserData = UserData;

                $scope.selectCheck = function (mktId) {

                    if ($scope.isChecked(mktId)) {
                        _.remove($scope.checkModel, function (n) {
                            return n == mktId;
                        });
                    } else {
                        $scope.checkModel.push(mktId);
                    }

                    $scope.model = _.join($scope.checkModel, [separator = ', ']);

                    return false;
                };

                $scope.isChecked = function (mktId) {
                    return _.includes($scope.checkModel, mktId);
                };

                $scope.updateCheckModel = function () {
                    $scope.checkModel = _.filter(_.map(_.split($scope.model.replace(/ /g, ""), ","), function (v) { return Number(v); }), function (v) { return v > 0 });
                };



                $scope.leftRightClass = $scope.leftRight == "left" ? "dropdown-menu-left" : "dropdown-menu-right";

            }],
            template: '\
<div id="{{id}}" class="input-group {{className}}">\
    <input id="{{id}}_input"  class="form-control" aria-label="select from saved Market No.\'s" ng-model="model" ng-change="updateCheckModel()"  />\
    <div class="input-group-btn" uib-dropdown>\
        <button id="{{id}}_button" type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="!UserData.markets.any()">\
            <i class="fa fa-list-ul"></i> <span class="caret"></span>\
        </button>\
        <ul class="dropdown-menu {{leftRightClass}}" uib-dropdown-menu role="menu" aria-labelledby="{{id}}_button" ng-click="$event.stopPropagation()" style="min-width: 250px;">\
            <li ng-repeat="mkt in UserData.markets.get()"><div class="col-xs-1"><input type="checkbox" ng-click="selectCheck(mkt.marketId)" ng-checked="isChecked(mkt.marketId)" /></div><div class="col-xs-10"><a ng-click="selectCheck(mkt.marketId)"><strong>{{mkt.marketId}}</strong> - {{mkt.marketName}}</a></div></li>\
        </span>\
    </div>\
</div>'
        };

        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('marketPicker', marketPicker);

    marketPicker.$inject = ['$log'];

    function marketPicker($log) {
        // Usage:
        //     <market-picker ng-model="bindToVariable"></market-picker>
        //      - ng-model      REQUIRED        the variable to bind to
        //      - id            OPTIONAL        the id of the resulting element
        //                                      NOTE: the internal inbput box will have id appended with "_input" 
        //                                            the dropdown button will have id appended with "_button"
        //      - class         OPTIONAL        class name to apply to outer wrapper of resulting element
        //      - left-right    OPTIONAL        controls how dropdown is aligned, left to left side button or right to right side of button (defaults to "right")
        //
        // Creates:
        //     textbox with market dropdown button
        var directive = {
            restrict: 'E',
            replace: true,
            scope: {
                model: '=ngModel',
                id: '@',
                className: '@class',
                leftRight: '@',
                callBack: '@'
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            link: function(scope, el, attrs)
            {
                el.bind("keyup", function (code) {
                    if (code.keyCode == 13) {
                        if (scope.callBack != undefined) {
                            scope.$apply();
                            $("#" + scope.callBack).click();
                        }
                    }
                    });
            },
            controller: ['$scope', 'UserData', function ($scope, UserData) {
                $scope.id = $scope.id || "mktno-picker-" + new Date().getTime();
                $scope.UserData = UserData;
                $scope.pickOne = function (rssdId) {
                    $scope.model = rssdId;
                };
                $scope.leftRightClass = $scope.leftRight == "left" ? "dropdown-menu-left" : "dropdown-menu-right";
            }],
            template: '\
<div id="{{id}}" class="input-group {{className}}">\
    <input id="{{id}}_input"  class="form-control" aria-label="select from saved Market No.\'s" ng-model="model"  />\
    <div class="input-group-btn" uib-dropdown>\
        <button id="{{id}}_button" type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="!UserData.markets.any()">\
            <i class="fa fa-list-ul"></i> <span class="caret"></span>\
        </button>\
        <ul class="dropdown-menu {{leftRightClass}}" uib-dropdown-menu role="menu" aria-labelledby="{{id}}_button">\
            <li ng-repeat="mkt in UserData.markets.get()"><a ng-click="pickOne(mkt.marketId)"><strong>{{mkt.marketId}}</strong> - {{mkt.marketName}}</a></li>\
        </span>\
    </div>\
</div>'
        };

        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('pageSizer', pageSizer);

    pageSizer.$inject = ['$log', 'bowser'];

    function pageSizer($log, bowser) {
        // Usage:
        //      <table class="cassidi-table" st-table ...>
        //          <thead>...</thead>
        //          <tbody>
        //              <tr ng-repeat="row in rowsCollection">
        //              ...
        //              </tr>
        //          </tbody>
        //          <tfoot>
        //              <tr>
        //                  <td colspan="100%">
        //                      <st-pagination st-items-by-page="pageSize"></st-pagination>
        //                      <page-sizer ng-if="rowsCollection" ng-model="pageSize" data="rowsCollection" one-page="true"></page-sizer>
        //                  </td>
        //              <tr>
        //          </tfoot>
        //      </table>
        // 
        // Creates:
        // 
        var directive = {
            link: fnLink,
            restrict: 'E',
            replace: true,
            templateUrl: 'AppJs/common/directives/pageSizer.html',
            scope: {
                id: "@?",
                ngModel: "=",
                rowCount: "=",
                onePage: "="
            }
        };
        return directive;

        function fnLink(scope, element, attrs) {
            var setCurrentSize = function (sz) {
                if (!sz) return;
                scope.currentSize = sz;
                scope.ngModel = sz.perPage;
  
            };

            var fnSetInitialIndex = function () {
                if (scope.rowCount <= 30) {
                    setCurrentSize();
                    scope.pageSizes = 0;
                    return;
                }
                var availablePageSizes = [],
                    isOldIE = bowser.msie && bowser.version <= 11;

                if (scope.rowCount > 30) availablePageSizes.push({ text: "30 per page", perPage: 30 });
                if (scope.rowCount > 75) availablePageSizes.push({ text: "75 per page", perPage: 75 });
                if (scope.rowCount > 125) availablePageSizes.push({ text: "125 per page", perPage: 125 });
                if (!isOldIE && scope.rowCount > 250) availablePageSizes.push({ text: "250 per page", perPage: 250 });
                if (!isOldIE || (isOldIE && scope.rowCount <= 250)) availablePageSizes.push({ text: "all records", perPage: scope.rowCount });

                scope.pageSizes = availablePageSizes;

                if (!!scope.onePage || scope.rowCount < 35)
                    scope.initialIndex = availablePageSizes.length - 1;
                else
                    scope.initialIndex = 0;

                setCurrentSize(scope.pageSizes[scope.initialIndex]);
            };

            scope.$watch('rowCount', function (newValue, oldValue) {
                //$log.info("$watch::rowCount (" + scope.id + ")", newValue);
                if (newValue != oldValue)
                    fnSetInitialIndex();
            });

            scope.id = _.trim(scope.id) || "pg-szr-" + new Date().getTime();

            scope.setCurrentSize = setCurrentSize;

            if (scope.rowCount)
                fnSetInitialIndex();
        }
    };
})();
;
(function () {
    angular.module('app')
           .directive('rssdMultiPicker', rssdMultiPicker);

    rssdMultiPicker.$inject = ['$log'];

    function rssdMultiPicker($log) {
        // Usage:
        //     <rssd-multipicker ng-model="bindToVariable"></rssd-picker>
        //      - ng-model      REQUIRED        the variable to bind to
        //      - id            OPTIONAL        the id of the resulting element
        //                                      NOTE: the internal inbput box will have id appended with "_input" 
        //                                            the dropdown button will have id appended with "_button"
        //      - class         OPTIONAL        class name to apply to outer wrapper of resulting element
        //      - left-right    OPTIONAL        controls how dropdown is aligned, left to left side button or right to right side of button (defaults to "right")
        //
        // Creates:
        //     textbox with RSSD picker dropdown button
        var directive = {
            restrict: 'E',
            replace: true,
            scope: {
                model: '=ngModel',
                id: '@',
                className: '@class',
                leftRight: '@',
                name: "@",
                callFn: '&',
                blur: '&pickerBlur',
                isTextArea: '=',
                disabled: '=',
                instList: '=?'
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            controller: ['$scope', 'UserData', function ($scope, UserData) {

                $scope.checkModel = [];

                if ($scope.instList == null)
                    $scope.instList = UserData.institutions.get();

                $scope.UserData = UserData;
                $scope.leftRightClass = $scope.leftRight == "left" ? "dropdown-menu-left" : "dropdown-menu-right";

                $scope.selectCheck = function (rssdId, $event) {

                    if ($scope.isChecked(rssdId)) {
                        _.remove($scope.checkModel, function (n) {
                            return n == rssdId;
                        } );
                    } else {
                        $scope.checkModel.push(rssdId);
                    }
                    
                    
                    $event.stopPropagation();
                    $event.target.blur();

                    return false;
                };


                $scope.isChecked = function (rssdId) {
                    return _.includes($scope.checkModel, rssdId);
                };

                $scope.commitChanges = function() {
                    $scope.model = _.join($scope.checkModel, [separator = ', ']);
                    $scope.callFn({ 'targets': $scope.model });

                    $scope.checkModel = [];
                };


            }],
            templateUrl: '/AppJs/common/directives/rssdMultiPicker.html'
        };


        return directive;
    };
})();
;
    (function () {
    angular.module('app')
           .directive('rssdPicker', rssdPicker);

    rssdPicker.$inject = ['$log'];

    function rssdPicker($log) {
        // Usage:
        //     <rssd-picker ng-model="bindToVariable"></rssd-picker>
        //      - ng-model      REQUIRED        the variable to bind to
        //      - id            OPTIONAL        the id of the resulting element
        //                                      NOTE: the internal inbput box will have id appended with "_input" 
        //                                            the dropdown button will have id appended with "_button"
        //      - class         OPTIONAL        class name to apply to outer wrapper of resulting element
        //      - left-right    OPTIONAL        controls how dropdown is aligned, left to left side button or right to right side of button (defaults to "right")
        //
        // Creates:
        //     textbox with RSSD picker dropdown button
//Rolledback the numeric change, it was removing the keypad and 
		var directive = {
            restrict: 'E',
            replace: true,
            scope: {
                model: '=ngModel',
                id: '@',
                className: '@class',
                leftRight: '@',
				blur: '&pickerBlur',
                typeaheadOrgType: '@pickerOrgType',
                name: "@",
				callBack: '@',
                onKey: '=',
                onKeyObject: '=',
                disabled: '=',
				instList: '=?'
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            link: function (scope, el, attrs) {
                el.bind("keyup", function (code) {
                    if(code.keyCode == 13) {
                        if (scope.callBack != undefined) {
                            scope.$apply();
                            $("#" + scope.callBack).click();
                        }
                    } 
                    });
                // If the input control is changed to a new child location below in the template this el[0].children[X] needs to be updated.
                if (attrs.hasFocus != undefined && attrs.hasFocus == "yes")
					document.getElementById(el[0].children[0].id).focus();
            },
			controller: ['$scope', 'UserData', 'AdvInstitutionsService', '$attrs', function ($scope, UserData, AdvInstitutionsService, $attrs) {
				if ($attrs.maxTypeAheadItems != undefined && !isNaN($attrs.maxTypeAheadItems)) {
					$scope.maxTypeAheadsReturned = $attrs.maxTypeAheadItems;
				}
				else {
					$scope.maxTypeAheadsReturned = 8;
                }

                if ($attrs.useAltOrgs != undefined) {
                    $scope.useAltOrgs = ($attrs.useAltOrgs == 'true');
                }
                else {
                    $scope.useAltOrgs = false;
                }


				if ($scope.instList == null)
                    $scope.instList = UserData.institutions.get();

                $scope.id = $scope.id || "rssd-picker-" + new Date().getTime();

                $scope.pickOne = function (rssdId) {
                    $log.info('$scope.model', $scope.model);
                    $scope.model = rssdId;
                    if ($scope.onKey != undefined) {
                        $scope.onKey($scope.onKeyObject, $scope.model);
					}
					$scope.forceInputEvents();
                };

                $scope.forceNumber = function() {
                    $scope.model = $scope.model.replace(/\D/g, '');
                    if ($scope.onKey != undefined) {
                        $scope.onKey($scope.onKeyObject, $scope.model);
					}					
				};

				$scope.getRSSDsFromPartial = function (partialRSSD) {
                    return AdvInstitutionsService.getRSSDIdFromPartial(partialRSSD, $scope.maxTypeAheadsReturned, $scope.typeaheadOrgType, $scope.useAltOrgs);
				};

				$scope.leftRightClass = $scope.leftRight == "left" ? "dropdown-menu-left" : "dropdown-menu-right";

				$scope.forceInputEvents = function (rssdVal) {
					var fldId = $('#' + $scope.id.trim() + '_input');	
					if (fldId.length > 0) {
						setTimeout(function () { $(fldId).blur().focus(); }, 100); // cause any picker field blur event handlers to execute while ending with focus
					}
				};
								
            }],
            template: '\
<div id="{{id.trim()}}" class="input-group {{className}}">\
    <input id="{{id.trim()}}_input" typeahead-on-select="forceInputEvents($model)" class="form-control" name="{{name}}" uib-typeahead="rssdChoice for rssdChoice in getRSSDsFromPartial($viewValue)" aria-label="select from saved RSSDID\'s" ng-model="model" ng-change="forceNumber()" ng-blur="blur($event)" ng-disabled=\"disabled\" />\
    <div class="input-group-btn" uib-dropdown>\
        <button id="{{id.trim()}}_button" type="button" class="btn btn-default form-control"  uib-dropdown-toggle ng-disabled="instList.length == 0">\
            <i class="fa fa-list-ul"></i> <span class="caret"></span>\
        </button>\
        <ul class="dropdown-menu {{leftRightClass}}" uib-dropdown-menu role="menu" aria-labelledby="{{id.trim()}}_button">\
            <li ng-repeat-start="inst in instList" title="{{inst.city}},{{inst.stateCode}}"><a ng-click="pickOne(inst.rssdId)"><strong>{{inst.rssdId}}</strong> - <i class="fa fa-university" ng-show="inst.class == \'BHC\' || inst.class == \'THC\' || inst.class == \'SLHC\'"></i> <strong>{{inst.class}}</strong> - {{inst.name.length>20 ? inst.name.substr(0,18)+"&hellip;" : inst.name}}</a>\
            <li class="indent" ng-repeat-end ng-repeat="org in inst.orgs" title="{{org.city}},{{org.stateCode}}"><a ng-click="pickOne(org.rssdId)"><strong>{{org.rssdId}}</strong> - <strong>{{org.class}}</strong> - {{org.name.length>20 ? org.name.substr(0,18)+"&hellip;" : org.name}}</a>\
            </li>\
        </ul>\
    </div>\
</div>'
		};		
		return directive;
    };
    })();

;

(function () {
    angular.module('app')
           .directive('spinnerUntil', spinnerUntil);

    spinnerUntil.$inject = ['$log'];

    function spinnerUntil($log) {
        // Usage:
        //          <ANY spinner-until="booleanVariable"> ... </ANY>
        // 
        // Creates:
        // 
        var elt,
            directive = {
                link: link,
                restrict: 'A',
                replace: false,
                scope: {
                    spinnerUntil: "="
                }
            };
        return directive;

        function link(scope, element, attrs) {
            elt = angular.element(element);
            scope.spinnerUntil = !!scope.spinnerUntil;

            toggleSpinner(scope.spinnerUntil);

            scope.$watch('spinnerUntil', function (newValue, oldValue) {
                toggleSpinner(!!newValue);
            });
        }

        function toggleSpinner(isOn) {
            var spinClass = "spin-baby";
            if (isOn)
                elt.removeClass(spinClass);
            else
                elt.addClass(spinClass);
        }
    };
})();
;
(function () {
    angular.module('app')
           .directive('statePicker', statePicker);

    statePicker.$inject = [];

    function statePicker() {
        // Usage:
        //          <state-picker state="stateObject" />
        // 
        // Creates:
        //          A two-part button for selecting either the state itself or for navigating to a list of the state's counties
        // 
        var directive = {
            restrict: 'E',
            replace: true,
            templateUrl: '/AppJs/common/directives/statePicker.html',
            scope: {
                state: '='
            },
            controller: ['$scope', function ($scope) {
            }]
        };
        return directive;
    };
})();;
// Adds the CSS classes that act as a reference to hook the printable parts of the page into the print CSS file.

function MakePrintable() 
{
    // Find all of the printableContainer elements, set class on each of their parents and each of their child elements.
    // The print CSS will use these to target the elements for special print treatment.
    var printContainers = $(".printableContainer");
    if (!printContainers || printContainers.length == 0) { return; }
    $("body").first().addClass("printAsReport");
    $(printContainers).find("*:not(.unprintable)").addClass("printable");
    $(printContainers).parents().addClass("printableContainerParent");
};

(function () {
    angular.module('app')
           .directive('buyerHeader', buyerHeader);

    buyerHeader.$inject = ['ProFormaService', '$log'];

    function buyerHeader(ProFormaService, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: '<div class="pro-forma-header pro-forma-buyer-header">\
<span ng-class="{\'label label-primary\': local.hasBuyer()}" uib-tooltip="{{local.getBuyerText()}}" tooltip-placement="left">Buyer</span> \<div ng-if="local.showClearLink()" class="text-center"><a href="#" ng-click="local.clearBuyer()" ng-disabled="!local.hasBuyer()">clear</a></div>\
</div>',
            scope: {
                clear: "&?"
            }
        };
        return directive;

        function link(scope, element, attrs) {
            scope.local = {
                showClearLink: function () {
                    return ProFormaService.hasBuyer() || ProFormaService.hasTarget();
                },

                hasBuyer: ProFormaService.hasBuyer,

                getBuyerText: function() {
                    return ProFormaService.hasBuyer() ? ProFormaService.selections.buyer.name : null;
                },

                clearBuyer: function () {
                    //if (scope.clear) {
                    //    scope.clear();
                    //} else {
                        ProFormaService.clearBuyer();
                    //}
                }
            };
        }
    };
})();
;
(function () {
    angular.module('app')
           .directive('buyerSelector', buyerSelector);

    buyerSelector.$inject = ['ProFormaService', '$log'];

    function buyerSelector(ProFormaService, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var errors = {};
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            templateUrl: 'AppJs/common/proForma/buyerSelector.html',
            scope: {
                buyer: "=",
                form: "="
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            }
        };
        return directive;

        function link(scope, element, attrs) {
            scope.selections = ProFormaService.selections;

            scope.isChecked = function () {
                return ProFormaService.selections.buyer != null && ProFormaService.selections.buyer.rssdId === scope.buyer.rssdId;
            };

            scope.setBuyer = function () {
                if (!scope.isChecked()) {
                    ProFormaService.selections.buyer = scope.buyer;
                    ProFormaService.selections.evaluate();
                }
            };

        }
    };
})();
;

(function () {
    angular.module('app')
           .directive('commonMarketsButton', commonMarketsButton);

    commonMarketsButton.$inject = ['ProFormaService', '$state', '$log'];

    function commonMarketsButton(ProFormaService, $state, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: '<span class="pro-forma-header pro-forma-common-markets">\
<button class="btn btn-primary btn-sm" ng-disabled="!local.enableIt()" ng-click="local.go()"><div class="small">View</div>Common Markets</button>\
</span>',
        };
        return directive;

        function link(scope, element, attrs) {
            scope.local = {
                enableIt: function () {
                    return ProFormaService.hasBuyer() && ProFormaService.hasTarget() && !ProFormaService.selections.hasErrors();
                },

                go: function () {
                    var buyer = ProFormaService.selections.buyer.rssdId,
                        targets = _.join(_.flatMap(ProFormaService.selections.targets, "rssdId"), ",");

                    $state.go('root.analysis.common-markets', { buyer: buyer, targets: targets, branches: [] });
                }
            };
        }
    };
})();
;

(function () {
    angular.module('app')
           .directive('generateProformaReport', generateProformaReport);

    generateProformaReport.$inject = ['ProFormaService', '$log', '$state', '$stateParams', 'toastr','$window'];

    function generateProformaReport(ProFormaService, $log, $state, $stateParams, toastr, $window) {
        // Usage:
        // 
        // Creates:
        // 



        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: '<span class="pro-forma-header pro-forma-common-markets pro-forma-save-selections">\
                        <button class="btn btn-primary btn-sm" ng-disabled="!local.enableIt()" ng-click="local.go()"><i class="fa fa-file-pdf-o"></i> Pro Forma<br /><small>Generate PDF Report</small></button>\
                        </span>',
            scope: {
                save: "&?",
                clear: "&?",
                go: "&?"
            }
        };
        return directive;

        function link(scope, element, attrs) {
            scope.local = {
                enableIt: function () {
                    return ( ProFormaService.hasBuyer() && ProFormaService.hasTarget()) && !ProFormaService.selections.hasErrors();
                },

                go: function () {

                    var buyer = ProFormaService.selections.buyer.rssdId,
                        targets = _.join(_.flatMap(ProFormaService.selections.targets, "rssdId"), ",");
                    var marketNum = $stateParams.market;

                    //$state.go('root.analysis.generateProformaReport', { marketNum: marketNum, buyer: buyer, targets: targets });
                    //need to change this from window.open to something else
                    $window.open('/report/proformacommonmarket?markets=' + marketNum + '&buyer=' + buyer + '&target=' + targets, '_blank');
                    toastr.success("Report generated and ran in a new window.");
                }


            };
        }
    };
})();



;

(function () {
    angular.module('app')
           .directive('generateProformaCommonMarketReport', generateProformaCommonMarketReport);

    generateProformaCommonMarketReport.$inject = ['ProFormaService', '$log', '$state', '$stateParams', 'toastr', '$window','UserData'];

    function generateProformaCommonMarketReport(ProFormaService, $log, $state, $stateParams, toastr, $window, UserData) {
        // Usage:
        // 
        // Creates:
        // 



        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: '<span class="pro-forma-header pro-forma-common-markets pro-forma-save-selections">\
                        <button class="btn btn-primary btn-sm" ng-disabled="!local.enableIt()"  ng-click="local.go()"><i class="fa fa-file-pdf-o"></i> Pro Forma<br /><small>Generate PDF Report</small></button>\
                        </span>',
            scope: {
                save: "&?",
                clear: "&?",
                go: "&?"
            }
        };
        return directive;

        function link(scope, element, attrs) {
            scope.local = {
                enableIt: function () {
                    return ((UserData.markets.hasMarket() && $stateParams.buyer != null && $stateParams.targets != null ) && !ProFormaService.selections.hasErrors());
                },

                go: function () {
                    var markets = UserData.markets.get();
                    var marketNum = _.join(_.flatMap(markets, "marketId"), ",");
                    //need to change this from window.open to something else
                    $window.open('/report/proformacommonmarket?markets=' + marketNum + '&buyer=' + $stateParams.buyer + '&target=' + $stateParams.targets, '_blank');
                    toastr.success("Report generated and ran in a new window.");
                }


            };
        }
    };
})();



;
(function () {
    angular.module('app')
           .directive('institutionSelector', institutionSelector);

    institutionSelector.$inject = ['UserData', '$log'];

    function institutionSelector(UserData, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var errors = {};
        var directive = {
            restrict: 'E',
            replace: true,
            template: '\
<span ng-class="{isButton: \'institution-btn\'}" class="pro-forma-selector pro-forma-market">\
    <input ng-if="!isButton" type="checkbox" name="institution" ng-checked="local.isSelected()" ng-click="local.toggleinstitution(this)" />\
    <button ng-if="isButton" class="btn btn-default btn-sm" role="button" ng-click="local.toggleinstitution()" title="{{local.isSelected() ? \'institution is saved, click to remove\' : \'institution is not saved, click to save\'}}">\
        <i class="fa fa-lg" ng-class="{\'fa-check-square-o\': local.isSelected(), \'fa-square-o\': !local.isSelected()}"></i> <span ng-if="!local.isSelected()">Save institution</span><span ng-if="local.isSelected()">Remove institution</span>\
    </button>\
</span>',
            scope: {
                institution: "=",
                isButton: "="
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            controller: ["$scope", "UserData", "$log", function ($scope, UserData, $log) {
                angular.extend($scope, {
                    local: {
                        institution: $scope.institution,
                        isSelected: function () {
                            return UserData.institutions.isSaved($scope.local.institution);
                        },
                        toggleinstitution: function (chkBox) {
                            if (this.isSelected())
                            {
                                UserData.institutions.removebyID($scope.local.institution.rssdId);
                            }
                            else
                                UserData.institutions.save($scope.local.institution);
                        }
                    }
                });
            }]
        };
        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('marketHeader', marketHeader);

    marketHeader.$inject = ['UserData', '$log'];

    function marketHeader(UserData, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var errors = {};
        var directive = {
            restrict: 'E',
            replace: true,
            template: '<div class="pro-forma-header pro-forma-market-header text-center" title="save (and un-save) markets to your market list">\
Save to Session\<div ng-if="local.showClearLink()" class="text-center" title="de-select markets from the current list"><a href="#" ng-click="local.clearMarkets()">clear</a></div>\
</div>',
            scope: {
                markets: "="
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            controller: ["$scope", "UserData", "$log", function ($scope, UserData, $log) {
                if (!$scope.markets || !angular.isArray($scope.markets)) throw "The market-header element's markets property must be set an array of market items.";

                angular.extend($scope, {
                    local: {
                        markets: $scope.markets,
                        showClearLink: function () {
                            return UserData.markets.any($scope.local.markets);
                        },

                        clearMarkets: function () {
                            UserData.markets.remove($scope.local.markets);
                        }
                    }
                });
            }]
        };
        return directive;
    };
})();
;
(function () {
    angular.module('app')
           .directive('marketSelector', marketSelector);

    marketSelector.$inject = ['UserData', '$log'];

    function marketSelector(UserData, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var errors = {};
        var directive = {
            restrict: 'E',
            replace: true,
            template: '\
<span ng-class="{isButton: \'market-btn\'}" class="pro-forma-selector pro-forma-market">\
    <input ng-if="!isButton" type="checkbox" name="market" ng-checked="local.isSelected()" ng-click="local.toggleMarket(this)" title="{{local.isSelected() ? \'Market is saved\' : \'Select to save\'}} ({{local.market.marketName}})" />\
    <button ng-if="isButton" class="btn btn-success btn-sm" role="button" ng-disabled="local.isSelected()" ng-click="local.toggleMarket()" title="{{local.isSelected() ? \'Market is saved\' : \'Market is not saved, click to save\'}} ({{local.market.marketName}})">\
        Save Market <i class="fa fa-arrow-circle-right" style="margin-top: 5px;"></i>\
    </button>\
</span>',
            scope: {
                market: "=",
                isButton: "="
                /*
                 * item: "=item" (abbreviated to /item: "="/) means attribute item on the buyer-selector element
                 * = --> set attribute to object from parent
                 * & --> set attribute to method from parent
                 * @ --> set attribute to a string value
                 */
            },
            controller: ["$scope", "UserData", "$log", function ($scope, UserData, $log) {
                angular.extend($scope, {
                    local: {
                        market: $scope.market,
                        isSelected: function () {
                            return UserData.markets.isSaved($scope.local.market.marketId);
                        },
                        toggleMarket: function (chkBox) {
                            if(this.isSelected())
                                UserData.markets.remove($scope.local.market.marketId);
                            else
                                UserData.markets.save($scope.local.market);
                        }
                    }
                });
            }]
        };
        return directive;
    };
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('ProFormaService', ProFormaService);

    ProFormaService.$inject = ['toastr', 'UserData', '$timeout', '$log'];

    function ProFormaService(toastr, UserData, $timeout, $log) {
        var service = {
            selections: {
                buyer: null,
                targets: [],
                errors: [],
                evaluate: evaluateSelections,
                hasBuyerError: hasBuyerError,
                hasTargetError: hasTargetError,
                hasErrors: hasErrors,
                reset: resetSelections,
                clearBuyer: clearBuyer,
                clearTargets: clearTargets,
                save: saveToUserData,
                load: loadFromUserData
            },
            hasBuyer: hasBuyer,
            hasTarget: hasTarget,
            hasAnySelection: hasAnySelection,
            toggleBuyer: toggleBuyer,
            setBuyer: setBuyer,
            setTarget: setTarget,
            isBuyer: isBuyer,
            isTarget: isTarget,
            setBranch: saveTargetBranch,
            isSavedBranch: isSavedTargetBranch,
            removeBranch: removeTargetBranch,
            toggleBranch: toggleTargetBranch,
            clearBuyer: clearBuyer,
            clearTarget: clearTarget,
            clearTargets: clearTargets,
            resetSelections: resetSelections,
            runErrorCheck: runErrorCheck,
            //
            isError_SameEntity: isError_SameEntity, /* buyer, target */
            isError_SameTophold: isError_SameTophold, /* buyer, target */
            isError_BuyerControlsTarget: isError_BuyerControlsTarget, /* buyer, target */
            isError_NonTopholdBuyingTophold: isError_NonTopholdBuyingTophold, /* buyer, target */
            isError_TopholdBuyingBranches: isError_TopholdBuyingBranches, /* buyer, target */
            isError_TopholdAndSubsidiaryAsTargets: isError_TopholdAndSubsidiaryAsTargets /* target, otherTargets */
        };

        var errToast = null;

        return service;
        ////////////////

        function saveToUserData() {
            if (hasBuyer())
                UserData.buyerInstitutions.save(service.selections.buyer);

            if (hasTarget()) {
                _(service.selections.targets).forEach(function (t) {
                    UserData.targetInstitutions.save(t);
                });
            }

            //resetSelections();
        }


        function loadFromUserData() {

            resetSelections();

            if (UserData.buyerInstitutions.any())
                service.selections.buyer = $.extend(true, {}, UserData.buyerInstitutions.get()[0]);

               

            if (UserData.targetInstitutions.any()) {
                _(UserData.targetInstitutions.get()).forEach(function (t) {
                    service.selections.targets.push($.extend(true, {}, t));
                });
            }

        }


        function resetSelections() {
            service.selections.buyer = null;

            _.forEach(service.selections.targets, function(e) { e.branches = []});

            service.selections.targets = [];
            service.selections.errors = [];
        }


        function runErrorCheck(buyer, targets) {
            var errors = evaluateForErrors(buyer, targets);
            var friendlyErrors = [];
            _(errors).forEach(function(err) {
                friendlyErrors.push(getFriendlyError(err).reason);
            });

            return friendlyErrors;
        }

        function evaluateSelections() {
            service.selections.errors = evaluateForErrors(service.selections.buyer, service.selections.targets);

            if (errToast)
                toastr.clear(errToast);

            if (service.selections.errors.length == 1) {
                var msg = getFriendlyError(service.selections.errors[0]);
                errToast = toastr.error(msg.text, msg.title, { timeOut: 0 });
            } else if (service.selections.errors.length > 1) {
                var msgText = ""
                _(service.selections.errors).forEach(function (err) {
                    msgText += "<hr style='margin:0;margin-top:5px;'/>";
                    msgText += "<div>" + getFriendlyError(err).text + "</div>";
                });
                errToast = toastr.error(msgText, "Multiple Errors", { allowHtml: true, timeOut: 0 });
            }
        }

        function evaluateForErrors(buyer, targets) {
            var errors = [];

            // All rules require at least one target
            if (targets && targets.length > 0) {

                // Rules that apply to a buyer and a target
                if (buyer) {
                    _(targets).forEach(function (t) {

                        // These could all be true for a single buyer/target pair, so only report the first match
                        if (isError_SameEntity(buyer, t))
                            errors.push({ errCode: "sameEntity", id: buyer.rssdId });
                        else if (isError_SameTophold(buyer, t))
                            errors.push({ errCode: "sameParent", buyerId: buyer.rssdId, targetId: t.rssdId });
                        else if (isError_BuyerControlsTarget(buyer, t))
                            errors.push({ errCode: "buyerControlsTarget", buyerId: buyer.rssdId, targetId: t.rssdId });

                        if (isError_NonTopholdBuyingTophold(buyer, t))
                            errors.push({ errCode: "nonTopBuysTop", buyerId: buyer.rssdId, targetId: t.rssdId });

                        if (isError_TopholdBuyingBranches(buyer, t))
                            errors.push({ errCode: "topBuysBranches", buyerId: buyer.rssdId, targetId: t.rssdId });
                    });
                }

                // Rules that only apply to targets, but there must be 2 or more
                if (targets.length > 1) {

                    _(targets).forEach(function (t) {
                        _(targets).forEach(function (t2) {

                            if (t.rssdId != t2.rssdId && isError_TopholdAndSubsidiaryAsTargets(t, t2))
                                errors.push({ errCode: "topAndSubsAsTarget", topId: t.rssdId, subId: t2.rssdId });

                        });
                    });
                }
            }

            // Ensure we have only unique errors
            if (errors.length > 1)
                errors = _.uniqWith(errors, _.isEqual);

            return errors;
        }

        // Enables error condition display for buyer radio button
        function hasBuyerError(buyerId, errors) {
            errors = errors || service.selections.errors;

            var hasError = false;
            _(errors).forEach(function (err) {
                return !(hasError = (err.id && err.id == buyerId) || (err.buyerId && err.buyerId == buyerId));
            });
            return hasError;
        }

        // Enables error condition display for target checkbox
        function hasTargetError(targetId, errors) {
            errors = errors || service.selections.errors;

            var hasError = false;
            _(errors).forEach(function (err) {
                return !(hasError = (err.id && err.id == targetId) || (err.targetId && err.targetId == targetId || err.topId && err.topId == targetId || err.subId && err.subId == targetId));
            });
            return hasError;
        }

        function hasErrors() {
            return service.selections.errors && service.selections.errors.length > 0;
        }

        function hasBuyer() {
            return service.selections.buyer != null;
        }

        function hasTarget() {
            return service.selections.targets != null && service.selections.targets.length > 0;
        }

        function hasAnySelection() {
            return hasBuyer() || hasTarget();
        }

        function toggleBuyer(buyer) {
            if (isBuyer(buyer))
                clearBuyer();
            else
                service.selections.buyer = buyer;
        }

        function setBuyer(buyer) {
            service.selections.buyer = buyer;
        }

        function setTarget(target) {
            if (target && !isTarget(target))
                service.selections.targets.push(target);
        }

        function isBuyer(x) {
            var result = hasBuyer() && service.selections.buyer.rssdId == x.rssdId;
            return result;
        }

        function isTarget(x) {
            return hasTarget() && _.find(service.selections.targets, { rssdId: x.rssdId }) != null;
        }

        function toggleTargetBranch(inst, branch) {
            if (service.isTarget(inst)) {
                if (service.isSavedBranch(branch)) {
                    service.removeBranch(branch);
                } else {
                    service.setBranch(branch);
                }
            } else {
                service.setTarget(inst);
                service.setBranch(branch);
            }
        }

        function saveTargetBranch(branch) {

            var inst = _.find(service.selections.targets, { rssdId: branch.rssdId });
            if (inst) {
                if (!isSavedTargetBranch(branch)) {
                    if (inst.branches == null)
                        inst.branches = [];

                    inst.branches.push(branch);
                }
                return true;
            } else
                $log.error("Target Branch not saved");
            return false;
        }

        function isSavedTargetBranch(branch) {
            var inst = _.find(service.selections.targets, { rssdId: branch.rssdId });

            if (!inst)
                return false;

            return _.find(inst.branches, { branchId: branch.branchId });
        }



        function removeTargetBranch(branch) {

            var inst = _.find(service.selections.targets, { rssdId: branch.rssdId });
            _.pull(inst.branches, _.find(inst.branches, { branchId: branch.branchId }));


        }


        function clearBuyer() {
            service.selections.buyer = null;
            service.selections.evaluate();
        }

        function clearTarget(target) {
            if (target && isTarget(target)) {

                var targetFound = _.find(service.selections.targets, function (e) { return e.rssdId == target.rssdId });

                if (targetFound) {
                    targetFound.branches = [];
                    _.remove(service.selections.targets, { rssdId: target.rssdId });
                }
               
                
            }
                
        }

        function clearTargets() {
            _.forEach(service.selections.targets, function(e) { e.branches = []; });
            service.selections.targets = [];
            service.selections.evaluate();
        }

        function getBuyerTargetErrorsByBuyer(buyer, target) {
            return getBuyerTargetErrors(buyer, target, "buyer");
        }

        function getBuyerTargetErrorsByTarget(buyer, target) {
            return getBuyerTargetErrors(buyer, target, "target");
        }

        function getBuyerTargetErrors(buyer, target, context) {
            var errors = [];

            if (isError_SameEntity(buyer, target)) {
                if (context == "buyer")
                    errors.push("This institution is also specified as a target.");
                else if (context = "target")
                    errors.push("This institution is also specified as the buyer.");
                else
                    errors.push("The same institution, " + buyer.rssdId + ", has been selected as both buyer and target.");
            }

            if (isError_SameTophold(buyer, target)) {
                if (context == "buyer")
                    errors.push("This institution has the same holding company as a specified target (" + target.rssdId + ").");
                else if (context == "target")
                    errors.push("This institution has the same holding company as the buyer (" + buyer.rssdId + ").");
                else
                    errors.push("The buyer, " + buyer.rssdId + ", and target, " + target.rssdId + ", are under the same holding company.");
            }

            if (isError_BuyerControlsTarget(buyer, target)) {
                if (context == "buyer")
                    errors.push("This institution already controls a specified target, " + target.rssdId + ".");
                else if (context == "target")
                    errors.push("This institution is already controlled by the buyer, " + buyer.rssdId + ".");
                else
                    errors.push("The buyer, " + buyer.rssdId + ", already controls a specified target, " + target.rssdId + ".");
            }

            if (isError_NonTopholdBuyingTophold(buyer, target)) {
                if (context == "buyer")
                    errors.push("This institution is not a holding company, so it cannot target a holding company, " + target.rssdId + ".");
                else if (context == "target")
                    errors.push("This institution is a holding company, so it cannot be bought by a non-holding company, " + buyer.rssdId + ".");
                else
                    errors.push("An institution that is not a holding comppany, " + buyer.rssdId + ", cannot buy a holding company, " + target.rssdId + ".");
            }

            if (isError_TopholdBuyingBranches(buyer, target)) {
                if (context == "buyer")
                    errors.push("This institution is a tophold and cannot purchase branches from a target, " + target.rssdId + ".");
                else if (context == "target")
                    errors.push("This institution has branches that cannot be bought by a holding company, " + buyer.rssdId + ".");
                else
                    errors.push("A holding company, " + buyer.rssdId + ", cannot buy branches from a target, " + target.rssdId + ".");
            }

            return errors;
        }

        function getTargetErrorsForTarget(targets) {
            return getTargetErrors(targets, "target");
        }

        function getTargetErrors(targets, context) {
            var errors = [];

            angular.forEach(targets, function (target) {
                if (isError_TopholdAndSubsidiaryAsTargets(target, targets)) {
                    if (context == "target")
                        errors.push("A holding company, " + target.rssdId + ", and one of it subsidiaries cannot both be selected as targets.");
                    else
                        errors.push("A holding company and one or more of its subsidiaries cannot both be selected as targets.");
                }
            });

            return errors;
        }

        function isError_SameEntity(buyer, target) {
            return buyer.rssdId == target.rssdId;
        }

        function isError_SameTophold(buyer, target) {
            return !isError_SameEntity(buyer, target) && buyer.parentId == target.parentId;
        }

        function isError_BuyerControlsTarget(buyer, target) {
            return _.find(buyer.orgs, { rssdId: target.rssdId }) != null;
        }

        function isError_NonTopholdBuyingTophold(buyer, target) {
            return (buyer.class != "BHC" && buyer.class != "THC" && buyer.class != "SLHC") && (target.class == "BHC" || target.class == "THC" || target.class == "SLHC");
        }

        function isError_TopholdBuyingBranches(buyer, target) {
            return (buyer.class == "BHC" || buyer.class == "THC" || buyer.class == "SLHC") && target.branches != null && target.branches.length > 0;
        }

        function isError_TopholdAndSubsidiaryAsTargets(target, otherTargets) {
            if (!_.isArray(otherTargets)) otherTargets = [otherTargets];
            return (target.class == "BHC" || target.class == "THC" || target.class == "SLHC") && _.intersectionBy(target.orgs, otherTargets, "rssdId").length > 0;
        }

        function hasError(err) {
            return !!_.find(service.selections.errors, err);
        }

        function getFriendlyError(err) {
            var msg = { text: "", title: null };

            switch (err.errCode) {
                case "sameEntity":
                    msg.text = "The same institution, Fed ID  " + err.id + ", has been selected as both the buyer and target.";
                    msg.title = "Buyer same as Target";
                    msg.reason = "Warning: You have saved the same institution as both the buyer and target.";
                    break;
                case "sameParent":
                    msg.text = "A holding company, Fed ID  " + err.buyerId + ", and one of its subsidiaries, Fed ID " + err.targetId + ", have been selected.";
                    msg.title = "Same Parent for Both";
                    msg.reason = "Warning: You have saved a holding company, and one of its subsidiaries.";
                    break;
                case "buyerControlsTarget":
                    msg.text = "A buyer, " + err.buyerId + ", cannot buy a target, " + err.targetId + ", that it already controls";
                    msg.title = "Buyer Controls Target";
                    msg.reason = "Warning: You have saved a buyer and target that are under the same holding company.";
                    break;
                case "nonTopBuysTop":
                    msg.text = "A buyer, " + err.buyerId + ", that is *not* a holding company cannot buy a holding company, " + err.targetId;
                    msg.title = "Non-Tophold Buying Tophold";
                    msg.reason = "Warning: you have saved an institution as a buyer of a holding company. Please select a holding company as the buyer.";
                    break;
                case "topBuysBranches":
                    msg.text = "A tophold, " + err.buyerId + ", cannot buy a target, " + err.targetId + ", that is a branch";
                    msg.title = "Tophold Buying Branches";
                    msg.reason = "Warning: A holding company has been selected as the buyer for a purchase of branches from a target.  Please select a bank or thrift as the buyer.";
                    break;
                case "topAndSubsAsTarget":
                    msg.text = "Targets cannot include both a tophold, " + err.topId + ", and one of its subsidiaries, " + err.subId;
                    msg.title = "Tophold and Subsidiaries";
                    msg.reason = "Warning: you have saved a holding company and one of its subsidiaries.";
                    break;
                default:
                    msg.text = JSON.stringify(err);
                    break;
            }

            return msg;
        }
    }
})();
;

(function () {
    angular.module('app')
           .directive('saveSelectionCommonMarketButton', saveSelectionCommonMarketButton);

    saveSelectionCommonMarketButton.$inject = ['ProFormaService', '$log', '$state', 'UserData'];

    function saveSelectionCommonMarketButton(ProFormaService, $log, $state, UserData) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: '<span class="pro-forma-header pro-forma-common-markets pro-forma-save-selections">\
                        <button class="btn btn-primary btn-sm" ng-disabled="!local.enableCommonMarketIt()" ng-click="local.go()"><div class="small">View</div>Common Markets</button>\
                        <button class="btn btn-success btn-sm" ng-disabled="!local.enableIt()" ng-click="local.save()">Save Selections <i class="fa fa-arrow-circle-right fa-2x pull-right" style="margin-top:5px;"></i><div class="small">to Session</div></button>\
                        </span>',
            scope: {
                save: "&?",
                clear: "&?",
                go: "&?"
            }
        };
        return directive;

        function link(scope, element, attrs) {
            scope.local = {
                enableIt: function () {
                    return (ProFormaService.hasBuyer() || ProFormaService.hasTarget()) && !ProFormaService.selections.hasErrors();
                },

                enableCommonMarketIt: function () {
                    return (ProFormaService.hasBuyer() && ProFormaService.hasTarget()) && !ProFormaService.selections.hasErrors();
                },

                save: function () {
                    if (scope.save)
                        scope.save();
                    else
                        ProFormaService.selections.save();

                    //if (scope.clear)
                    //    scope.clear();
                    //else
                    //    ProFormaService.clearTargets();
                },

                go: function () {

                    var buyer = ProFormaService.selections.buyer.rssdId,
                        targets = _.join(_.flatMap(ProFormaService.selections.targets, "rssdId"), ","),
                        branches = _.join(_.flatMap(ProFormaService.selections.targets, function (target, i) { return _.flatMap(target.branches, function (e, i) { return e.branchId }) }));

                    $state.go('root.analysis.common-markets', { buyer: buyer, targets: targets, branches: branches });
                }


            };
        }
    };
})();
;

(function () {
    angular.module('app')
           .directive('saveSelectionsButton', saveSelectionsButton);

    saveSelectionsButton.$inject = ['ProFormaService', '$log'];

    function saveSelectionsButton(ProFormaService, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: '<span class="pro-forma-header pro-forma-save-selections">\
<button class="btn btn-success btn-sm" ng-disabled="!local.enableIt()" ng-click="local.save()">Save Selections <i class="fa fa-arrow-circle-right fa-2x pull-right" style="margin-top:5px;"></i><div class="small">to Session</div></button>\
</span>',
            scope: {
                save: "&?",
                clear: "&?"
            }
        };
        return directive;

        function link(scope, element, attrs) {
            scope.local = {
                enableIt: function () {
                    return (ProFormaService.hasBuyer() || ProFormaService.hasTarget()) && !ProFormaService.selections.hasErrors();
                },

                save: function () {
                    if (scope.save)
                        scope.save();
                    else
                        ProFormaService.selections.save();

                    //if (scope.clear)
                    //    scope.clear();
                    //else
                    //    ProFormaService.clearTargets();
                }
            };
        }
    };
})();
;

(function () {
    angular.module('app')
           .directive('targetHeader', targetHeader);

    targetHeader.$inject = ['ProFormaService', '$log'];

    function targetHeader(ProFormaService, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: '<div class="pro-forma-header pro-forma-target-header">\
<span ng-class="{\'label label-primary\': local.hasTarget()}" uib-tooltip="{{local.getTargetText()}}" tooltip-placement="left">Target</span>\<div ng-if="local.showClearLink()" class="text-center"><a href="#" ng-click="local.clearTargets()" ng-disabled="!local.hasTarget()">clear</a></div>\
</div>',
            scope: {
                clear: "&?"
            }
        };
        return directive;

        function link(scope, element, attrs) {
            scope.local = {
                showClearLink: function () {
                    return ProFormaService.hasBuyer() || ProFormaService.hasTarget();
                },

                hasTarget: ProFormaService.hasTarget,

                getTargetText: function () {

                    if (ProFormaService.hasTarget()) {
                        var targets = ProFormaService.selections.targets;

                        return _.join(_.map(targets, function (e) { return '- ' + e.name; }), [separator = '\r\n']);
                    }

                    return null;

                },

                clearTargets: function () {
                    //if (scope.clear) {
                    //    scope.clear();
                    //} else {
                        ProFormaService.clearTargets();
                    //}
                }
            };
        }
    };
})();
;
(function () {
    angular.module('app')
           .directive('targetSelector', targetSelector);

    targetSelector.$inject = ['ProFormaService', '$log'];

    function targetSelector(ProFormaService, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,            
            restrict: 'E',
            replace: true,
            templateUrl: 'AppJs/common/proForma/targetSelector.html',
            scope: {
                inst: "=",
                form: "="
            }
        };
        return directive;

        function link(scope, element, attrs) {

            scope.selections = ProFormaService.selections;

            scope.isChecked = function() {
                return ProFormaService.isTarget(scope.inst);
            };

            scope.toggleTarget = function () {
                if(!ProFormaService.isTarget(scope.inst))
                    ProFormaService.setTarget(scope.inst);
                else
                    ProFormaService.clearTarget(scope.inst);

                scope.selections.evaluate();
            };
        }
    };
})();
;
(function () {
    angular.module('app')
           .directive('sameEntityCheck', sameEntityCheck);

    sameEntityCheck.$inject = ['ProFormaService', '$log'];

    function sameEntityCheck(ProFormaService, $log) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'A',
            require: 'ngModel'
        };
        return directive;

        function link(scope, element, attrs, ctrl) {
            function validator(value) {
                var forTarget = scope.target ? true : false;
                $log.info("sameEntityCheck value", forTarget ? "for Target" : "for Buyer");
                //window.EL = element;
                //window.AT = attrs;
                //window.SC = scope;
                var isValid = true;

                if (scope.buyer && ProFormaService.hasTarget()) {
                    isValid = _.filter(ProFormaService.selections.targets, { rssdId: value.rssdId }).length == 0;
                    ctrl.$setValidity('sameEntity', isValid);
                }

                if (scope.target && ProFormaService.hasBuyer()) {
                    isValid = scope.target.rssdId != ProFormaService.selections.buyer.rssdId;
                    ctrl.$setValidity('sameEntity', isValid);
                }

                if (!isValid) $log.warn("NOT VALID!");

                return isValid ? value : undefined;
            }
            ctrl.$parsers.unshift(validator);
        }
    };
})();
;
/// <reference path="advanced/admin/AdminService.js" />
(function () {
    'use strict';

    angular
        .module('app.route-config', ['ui.router'])
        .config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {

            //$urlRouterProvider.deferIntercept(); //don't load views

            var inPrintMode = location.search.indexOf("print=true") > -1;

            $locationProvider.html5Mode(true);

            // For any unmatched url, redirect to /home/index
            $urlRouterProvider
                .when("/markets", "/markets/search")
                .when("/institutions", "/institutions/search")
                .when("/advanced", "/advanced/index")
                .when(/\/internal/, "/advanced/index")
                .otherwise("/index");

            // Now set up the states
            $stateProvider
                .state("root", {
                    abstract: true,
                    url: "/?print",
                    //template: "<div ui-view></div>",
                    views: {
                        "header": {
                            templateUrl: inPrintMode
                                ? "AppJs/public/views/navbar.print.html"
                                : "AppJs/public/views/navbar.html",
                            controller: "NavController"
                        }
                    },
                    data: {
                        isAdvanced: false,
                        requiresDisclaimer: true,
                        showPrintButton: true,
                        hideBreadCrumb: false
                    }
                })

                //PUBLIC
                .state("root.index", {
                    url: "index",
                    views: {
                        "content@": {
                            templateUrl: "AppJs/public/index.html",
                            controller: "PublicIndexController"
                        }
                    },
                    data: {
                        requiresDisclaimer: true,
                        showDisclaimerOnPageComplete: true,
                        displayName: "Index",
                        title: "Home",
                        showPrintButton: false
                    }
                })
                .state("root.error", {
                    url: "error",
                    views: {
                        "content@": {
                            templateUrl: "AppJs/public/generic.html",
                            controller: "errorController"
                        }
                    }
                })
                .state("root.404", {
                    url: "404",
                    views: {
                        "content@": {
                            templateUrl: "AppJs/public/generic.html",
                            controller: "errorController"
                        }
                    }
                })
                //-----------------------INSTITUTIONS-----------------------
                .state("root.institutions", {
                    url: "institutions",
                    views: {
                        "content@": {
                            templateUrl: "/AppJs/public/institutions/index.html",
                            controller: "InstitutionsController"
                        }
                    },
                    data: {
                        displayName: "Institutions"
                    }
                })
                .state("root.institutions.search", {
                    url: "/search",
                    templateUrl: "/AppJs/public/institutions/_search.html",
                    controller: "InstitutionSearchController",
                    data: {
                        displayName: "Search",
                        title: "Institutions - Search"
                    }
                })
                .state("root.institutions.browse", {
                    url: "/browse",
                    templateUrl: "/AppJs/public/institutions/_browse.html",
                    controller: "InstitutionBrowseController",
                    data: {
                        displayName: "Browse",
                        title: "Institutions - Browse"
                    }
                })
                .state("root.institutions.browsecounties", {
                    url: "/browse/:state",
                    templateUrl: "/AppJs/public/institutions/_browse.counties.html",
                    controller: "InstitutionBrowseCountiesController",
                    data: {
                        displayName: "Browse <strong>{{state}}</strong> Counties",
                        title: "Institutions - Browse Counties"
                    },
                    resolve: {
                        state: ['$stateParams', function ($stateParams) {
                            return $stateParams.state;
                        }]
                    }
                })
                .state("root.institutions.list", {
                    url: "/list?name&state&county&city&zip",
                    templateUrl: "/AppJs/public/institutions/_list.html",
                    controller: "InstitutionListController",
                    data: {
                        displayName: "List",
                        title: "Institutions - Results"
                    }
                })
                 .state("root.institutions.summary",
                {
                    abstract: true,
                    url: "/:rssd?name&state&county&city&zip",
                    templateUrl: "/AppJs/public/institutions/_summary.html",
                    controller: "InstitutionSummaryController",
                    data: {
                        displayName: "Details",
                        //abstractOverride: true
                        // breadcrumbProxy: "root.institutions.list"
                    },
                    resolve: {
                        institution: [
                            '$stateParams', 'InstitutionsService', function ($stateParams, InstitutionsService) {
                                return InstitutionsService.find($stateParams.rssd, $stateParams, { getDetail: true, getBranches: true });
                            }
                        ]
                    }
                })
                .state("root.institutions.summary.orgs", {
                    url: "/orgs",
                    templateUrl: "/AppJs/public/institutions/summary/_orgs.html",
                    controller: "InstitutionDetailOrgsController",
                    data: {
                        displayName: "Details",
                        title: "Institution Details"
                    },
                    resolve: {
                        institutionOrgs: [
                            '$stateParams', 'InstitutionsService', function ($stateParams, InstitutionsService) {
                                return InstitutionsService.find($stateParams.rssd, $stateParams, { getBranches: true });
                            }
                        ]
                    }
                })
                .state("root.institutions.summary.markets", {
                    url: "/markets",
                    templateUrl: "/AppJs/public/institutions/summary/_markets.html",
                    controller: "InstitutionDetailOpMarketController",
                    data: {
                        displayName: "Operating Market",
                        title: "Institution Details - Operating Market"
                    },
                    resolve: {
                        institutionMarkets: [
                            '$stateParams', 'InstitutionsService', function ($stateParams, InstitutionsService) {
                                return InstitutionsService.find($stateParams.rssd, null, { getOperatingMarkets: true });
                            }
                        ]
                    }
                })
                .state("root.institutions.summary.history", {
                    url: "/history",
                    templateUrl: "/AppJs/public/institutions/summary/_history.html",
                    controller: "InstitutionDetailHistoryController",
                    data: {
                        displayName: "History",
                        title: "Institution Details - History"
                    },
                    resolve: {
                        institutionHistory: [
                            '$stateParams', 'InstitutionsService', function ($stateParams, InstitutionsService) {
                                return InstitutionsService.find($stateParams.rssd, null, { getHistory: true });
                            }
                        ]
                    }
                })
                .state("root.institutions.commonmarkets", {
                    url: "/markets?buyer&target",
                    templateUrl: "/AppJs/public/institutions/_commonmarkets.html",
                    controller: "InstitutionCommonMarketsController",
                    data: {
                        displayName: "Common Markets",
                        title: "Institutions - Common Markets"
                    }
                })
                //-----------------------MARKETS-----------------------
                .state("root.markets", {
                    url: "markets",
                    views: {
                        "content@": {
                            templateUrl: "/AppJs/public/markets/index.html",
                            controller: "MarketsController"
                        }
                    },
                    data: {
                        displayName: "Markets"
                    }
                })
                .state("root.markets.search", {
                    url: "/search",
                    templateUrl: "/AppJs/public/markets/_search.html",
                    controller: "MarketSearchController",
                    data: {
                        displayName: "Search",
                        title: "Markets - Search"

                    }
                })
                .state("root.markets.browse", {
                    url: "/browse",
                    templateUrl: "/AppJs/public/markets/_browse.html",
                    controller: "MarketBrowseController",
                    data: {
                        displayName: "Browse",
                        title: "Markets - Browse"
                    }
                })
                .state("root.markets.browsecounties", {
                    url: "/browse/:state",
                    templateUrl: "/AppJs/public/markets/_browse.counties.html",
                    controller: "MarketBrowseCountiesController",
                    data: {
                        displayName: "Browse <strong>{{state}}</strong> Counties",
                        title: "Markets - Browse Counties"
                    },
                    resolve: {
                        state: ['$stateParams', function ($stateParams) {
                            return $stateParams.state;
                        }]
                    }
                })
                .state("root.markets.list", {
                    url: "/list?state&county&city&zip",
                    templateUrl: "/AppJs/public/markets/_list.html",
                    controller: "MarketListController",
                    data: {
                        displayName: "List",
                        title: "Markets - Results"
                    },
                    reload: true
                })
                .state("root.markets.detail", {
                    abstract: true,
                    url: "/:market",
                    //template: "<div ui-view></div>",
                    templateUrl: "/AppJs/public/markets/_detail.html",
                    controller: "MarketDetailController",
                    data: {
                        //displayName: "Details",
                        //abstractOverride: true
                        breadcrumbProxy: "root.markets.detail.definition"
                    },
                    resolve: {
                        marketDef: ["$stateParams", "MarketsService", function ($stateParams, MarketsService) {
                            return MarketsService.find($stateParams.market, { getDefinition: true });
                        }]
                    }
                })
                .state("root.markets.detail.definition", {
                    url: "",
                    templateUrl: "/AppJs/public/markets/details/_definition.html",
                    controller: "MarketDetailDefinitionController",
                    data: {
                        displayName: "Details",
                        title: "Market Details"
                    }
                })
                .state("root.markets.detail.hhi", {
                    url: "/hhi",
                    templateUrl: "/AppJs/public/markets/details/_hhi.html",
                    controller: "MarketDetailHhiController",
                    data: {
                        displayName: "HHI",
                        title: "Market Details - HHI"
                    },
                    resolve: {
                        marketHhi: ["$stateParams", "MarketsService", function ($stateParams, MarketsService) {
                            return MarketsService.find($stateParams.market, { getHhi: true });
                        }]
                    }
                })
                .state("root.markets.detail.map", {
                    url: "/map",
                    templateUrl: "/AppJs/public/markets/details/_map.html",
                    controller: "MarketDetailMapController",
                    data: {
                        displayName: "Map",
                        title: "Market Details - Map"
                    },
                    resolve: {
                        marketMap: ["$stateParams", "MarketsService", function ($stateParams, MarketsService) {
                            return MarketsService.find($stateParams.market, { getMap: true });
                        }]
                    }
                })
                .state("root.markets.detail.proformamap", {
                    url: "/proformamap",
                    templateUrl: "/AppJs/public/markets/details/_proformamap.html",
                    controller: "MarketProformaMapController",
                    data: {
                        displayName: "Proforma Map",
                        title: "Market Proforma - Map"
                    },
                    resolve: {
                        marketMap: ["$stateParams", "MarketsService", function ($stateParams, MarketsService) {
                            return MarketsService.find($stateParams.market, { getMap: true });
                        }]
                    }
                })
                .state("root.markets.detail.history", {
                    url: "/history",
                    templateUrl: "/AppJs/public/markets/details/_history.html",
                    controller: "MarketDetailHistoryController",
                    data: {
                        displayName: "History",
                        title: "Market Details - History"
                    },
                    resolve: {
                        marketHistory: ["$stateParams", "MarketsService", function ($stateParams, MarketsService) {
                            return MarketsService.find($stateParams.market, { getHistory: true });
                        }]
                    }
                })
                //-------------------------- ANALYSIS --------------------------
                .state("root.analysis", {
                    url: "analysis",
                    views: {
                        "content@": {
                            templateUrl: "AppJs/public/analysis/index.html",
                            controller: "PublicHhiAnalysisController"
                        }
                    },
                    data: {
                        displayName: "Analysis",
                        title: "Analysis"
                    }
                })
                .state("root.analysis.common-markets", {
                    url: "/common-markets?buyer&targets&branches",
                    templateUrl: "AppJs/public/analysis/_commonMarkets.html",
                    controller: "PublicCommonMarketsController",
                    data: {
                        displayName: "Common Markets"
                    }
                })
                .state("root.analysis.generateProformaReport", {
                    url: "^/report/proformacommonmarket?marketNum&buyer&targets&branches",
                    data: {
                        requiresDisclaimer: false,
                        displayName: "Proforma",
                        title: "Proforma"
                    }
                })
                //-------------------------- OTHER --------------------------
                .state("root.help", {
                    url: "help",
                    views: {
                        "content@": {
                            templateUrl: "AppJs/public/help/index.html"
                        }
                    },
                    data: {
                        requiresDisclaimer: false,
                        displayName: "Help",
                        title: "Help"
                    }
                })
                .state("root.privacy", {
                    url: "privacy",
                    views: {
                        "content@": {
                            templateUrl: "/AppJs/common/footer/privacy.html"
                        }
                    },
                    data: {
                        requiresDisclaimer: false,
                        displayName: "Privacy Policy",
                        title: "Privacy"
                    }
                })
                .state("root.legal", {
                    url: "legal",
                    views: {
                        "content@": {
                            templateUrl: "/AppJs/common/footer/legal.html"
                        }
                    },
                    data: {
                        requiresDisclaimer: false,
                        displayName: "Legal",
                        title: "Legal"
                    }
                })
                .state("root.login", {
                    url: "login?returnUrl&loggedOut",
                    views: {
                        "header@": {
                            templateUrl: "AppJs/public/views/navbar.login.html"
                        },
                        "content@": {
                            templateUrl: "AppJs/common/auth/signin.html",
                            controller: "LoginController"
                        }
                    },
                    data: {
                        requiresDisclaimer: true,
                        showDisclaimerOnPageComplete: true,
                        displayName: "Login",
                        title: "Login",
                        showPrintButton: false,
                        hideBreadCrumb: true,
                        requiresLogout: true
                    }
                })
                .state("root.logout", {
                    url: "logout",
                    views: {
                        "content@": {
                            template: "<h1>Logging Out</h1>"
                        }
                    },
                    data: {
                        requiresDisclaimer: false,
                        displayName: "Log Out",
                        title: "Log Out"
                    }
                })
                 .state("root.changepassword", {
                     url: "changepassword",
                     views: {
                         "content@": {
                             template: "<h1>changepassword</h1>"
                         }
                     },
                     data: {
                         requiresDisclaimer: false,
                         displayName: "changepassword",
                         title: "changepassword"
                     }
                 })
                .state("root.not-allowed", {
                    url: "not-allowed",
                    views: {
                        "content@": {
                            templateUrl: "AppJs/common/auth/notallowed.html",
                            controller: "NotAllowedController"
                        }
                    },
                    data: {
                        requiresDisclaimer: false,
                        displayName: "No Access",
                        title: "Access Not Allowed"
                    }
                })
                // ADVANCED
                .state("root.adv", {
                    abstract: true,
                    url: "advanced",
                    views: {
                        "header@": {
                            templateUrl: "AppJs/advanced/views/navbar.html",
                            controller: "NavController"
                        },
                        "content@": {
                            templateUrl: "AppJs/advanced/_layout.html"
                        }
                    },
                    data: {
                        isAdvanced: true,
                        displayName: "Home"
                    }
                })
                // ADVANCED -- INDEX
                .state("root.adv.index", {
                    url: "/index",
                    templateUrl: "AppJs/advanced/index/welcome.html",
                    controller: "WelcomeController",
                    data: {
                        requiresDisclaimer: false,
                        displayName: "Index"
                    }
                })
                // ADVANCED -- USER PROFILE
                .state("root.adv.userprofile", {
                    url: "/user-profile",
                    templateUrl: "AppJs/advanced/user-profile/index.html",
                    controller: "UserProfileController",
                    data: {
                        title: "User Profile",
                        displayName: "User Profile"
                    }
                })

                // ADVANCED -- INSTITUTIONS
                .state("root.adv.institutions", {
                    url: "/institutions",
                    templateUrl: "AppJs/advanced/institutions/index.html",
                    controller: "AdvInstitutionsController",
                    data: {
                        displayName: "Institutions"
                    }
                })
                 .state("root.adv.institutions.search", {
                     url: "/search",
                     templateUrl: "AppJs/advanced/institutions/views/_search.html",
                     controller: "AdvInstitutionsSearchController",
                     data: {
                         displayName: "Search",
                         title: "Institutions - Search"
                     }
                 })
                .state("root.adv.institutions.instsearch", {
                    url: "/instsearch",
                    templateUrl: "AppJs/advanced/institutions/views/_instsearch.html",
                    controller: "AdvInstitutionsFinderController",
                    data: {
                        displayName: "Search",
                        title: "Institutions - Search"
                    }
                })
                .state("root.adv.institutions.idsearch", {
                    url: "/idsearch",
                    templateUrl: "AppJs/advanced/institutions/views/_idsearch.html",
                    controller: "AdvInstitutionsIDSearchController",
                    data: {
                        displayName: "Search",
                        title: "Institutions - Search"
                    }
                })
                .state("root.adv.institutions.branchreport", {
                    url: "/branchreport",
                    templateUrl: "AppJs/advanced/institutions/views/_instBranchReport.html",
                    controller: "AdvInstitutionsBranchSearchController",
                    data: {
                        displayName: "Search",
                        title: "Branch Report - Search"
                    }
                })
                 .state("root.adv.institutions.browse", {
                     url: "/browse",
                     templateUrl: "AppJs/advanced/institutions/views/_browse.html",
                     controller: "AdvInstitutionsBrowseController",
                     data: {
                         displayName: "Browse",
                         title: "Institutions - Browse"
                     }
                 })

                  .state("root.adv.institutions.browsecounties", {
                      url: "/browse/:state",
                      templateUrl: "/AppJs/advanced/institutions/views/_browse.counties.html",
                      controller: "AdvInstitutionBrowseCountiesController",
                      data: {
                          displayName: "Browse <strong>{{state}}</strong> Counties",
                          title: "Institutions - Browse Counties"
                      },
                      resolve: {
                          state: ['$stateParams', function ($stateParams) {
                              return $stateParams.state;
                          }]
                      }
                  })
                .state("root.adv.institutions.list", {
                    url: "/list?rssd&fdic&name&marketNumber&state&city&county&international&zip&sdfCodeId",
                    templateUrl: "AppJs/advanced/institutions/views/_list.html",
                    controller: "AdvInstitutionsListController",
                    data: {
                        displayName: "List",
                        title: "Institutions - Results"
                    },
                    reload: true

                })

                .state("root.adv.institutions.sold", {
                    url: "/sold?rssd&buyer&target",
                    templateUrl: "AppJs/advanced/institutions/views/_instSold.html",
                    controller: "AdvInstitutionsSoldBranchController",
                    data: {
                        displayName: "Institution sale form",
                        title: "Institution sale form"
                    },
                    reload: true

                })

                .state("root.adv.institutions.fhclist", {
                    url: "/fhclist",
                    templateUrl: "AppJs/advanced/institutions/views/_fhclist.html",
                    controller: "AdvInstitutionsFHCListController",
                    data: {
                        displayName: "Financial Holding Companies",
                        title: "Financial Holding Companies"
                    },
                    reload: true

                })

                .state("root.adv.institutions.CiLoans", {
                    url: "/CiLoans",
                    templateUrl: "AppJs/advanced/institutions/views/_CiLoans.html",
                    controller: "advInstitutionsCILoansController",
                    data: {
                        displayName: "C I Loans",
                        title: "C I Loans"
                    },
                    reload: true
                })

                .state("root.adv.institutions.statedeposits", {
                    url: "/statedeposits",
                    templateUrl: "AppJs/advanced/institutions/views/deposits_state_rankings_criteria.html",
                    controller: "AdvInstitutionsStateDepositsListController",
                    data: {
                        displayName: "State Deposits Rankings",
                        title: "State Deposits Rankings"
                    },
                    reload: true

                })

                 .state("root.adv.institutions.branch", {
                     abstract: true,
                     url: "/:branchId",
                     templateUrl: "AppJs/advanced/institutions/views/branch/_viewBranch.html",
                     controller: "AdvInstitutionBranchController",
                     data: {
                         displayName: "Branch Details",
                         title: "Branch Details"
                     },
                     reload: true

                 })

	            .state("root.adv.institutions.branch.details", {
	                url: "/branch/details",
	                templateUrl: "/AppJs/advanced/institutions/views/branch/_details.html",
	                controller: "AdvInstitutionBranchDetailController",
	                data: {
	                    displayName: "Summary"
	                }
	            })

	            .state("root.adv.institutions.branch.geocode", {
	                url: "/branch/geocode",
	                templateUrl: "/AppJs/advanced/institutions/views/branch/_geocode.html",
	                controller: "AdvInstitutionBranchGeocodeController",
	                data: {
	                    displayName: "Geocode"
	                }
	            })

                .state("root.adv.institutions.branch.nearest", {
                    url: "/branch/nearest",
                    templateUrl: "/AppJs/advanced/institutions/views/branch/_nearest.html",
                    controller: "AdvInstitutionBranchNearestController",
                    data: {
                        displayName: "Find Nearest Branches"
                    }
                })

                .state("root.adv.institutions.branch.map", {
                    url: "/branch/map",
                    templateUrl: "/AppJs/advanced/institutions/views/branch/_map.html",
                    controller: "AdvInstitutionBranchMapController",
                    data: {
                        displayName: "Map Nearest Branches"
                    }
                })

                .state("root.adv.institutions.branch.marketdistances", {
                    url: "/branch/distances",
                    templateUrl: "/AppJs/advanced/institutions/views/branch/_marketdistances.html",
                    controller: "AdvInstitutionBranchMarketDistancesController",
                    data: {
                        displayName: "Market Branch Distances"
                    }
                })

                  //.state("root.adv.institutions.branch.edit", {
                  //    url: "/branch/edit/:branchId",
                  //    templateUrl: "AppJs/advanced/institutions/views/_editBranch.html",
                  //    controller: "AdvInstitutionsEditBranchController",
                  //    data: {
                  //        displayName: "Edit",
                  //        title: "Branch Report"
                  //    },
                  //    reload: true

                  //})
                  .state("root.adv.institutions.branchReportByArea", {
                      url: "/branchReport?state&city&county&marketNumber&zip",
                      templateUrl: "AppJs/advanced/institutions/views/_branchReportByArea.html",
                      controller: "AdvInstitutionsBranchAreaListController",
                      data: {
                          displayName: "Branch List",
                          title: "Branch Report"
                      },
                      reload: true

                  })
                  .state("root.adv.institutions.summary", {
                      abstract: true,
                      url: "/:rssd",
                      templateUrl: "/AppJs/advanced/institutions/views/_summary.html",
                      controller: "AdvInstitutionsSummaryController",
                      data: {
                          displayName: "Details"
                      },
                      reload: true
                  })
                    .state("root.adv.institutions.summary.details", {
                        url: "/details",
                        templateUrl: "/AppJs/advanced/institutions/views/summary/_details.html",
                        controller: "AdvInstitutionsDetailController",
                        data: {
                            displayName: "Details"
                        },
                        params: { fdic: null, fdicNotFound: null }
                    })

                  .state("root.adv.institutions.THFormation", {
                      url: "/:rssd",
                      templateUrl: "/AppJs/advanced/institutions/views/_tophold.html",
                      controller: "AdvTopholdEditController",
                      data: {
                          displayName: "Tophold Formation"
                      }
                  })

                .state("root.adv.institutions.BTCharter", {
                    url: "/:rssd",
                    templateUrl: "/AppJs/advanced/institutions/views/_institution.html",
                    controller: "AdvInstEditController",
                    data: {
                        displayName: "Bank Charter"
                    }
                })

                .state("root.adv.institutions.AttrUpdate", {
                    url: "/:rssd",
                    templateUrl: "/AppJs/advanced/institutions/views/_tophold.html",
                    controller: "AdvTopholdEditController",
                    data: {
                        displayName: "Attribute Update"
                    }
                })

                 .state("root.adv.institutions.summary.orgs", {
                     url: "/subs",
                     templateUrl: "/AppJs/advanced/institutions/views/summary/_orgs.html",
                     controller: "AdvInstitutionDetailOrgsController",
                     data: {
                         displayName: "Orgs",
                         title: "Institution Details"
                     },
                     reload: true
                 })
                .state("root.adv.institutions.summary.markets", {
                    url: "/markets",
                    templateUrl: "/AppJs/advanced/institutions/views/summary/_markets.html",
                    controller: "AdvInstitutionDetailOpMarketController",
                    data: {
                        displayName: "Operating Market",
                        title: "Institution Details - Operating Market"
                    }
                })
                .state("root.adv.institutions.summary.history", {
                    url: "/history",
                    templateUrl: "/AppJs/advanced/institutions/views/summary/_history.html",
                    controller: "AdvInstitutionDetailHistoryController",
                    data: {
                        displayName: "History",
                        title: "Institution Details - History"
                    }
                })
                .state("root.adv.institutions.summary.pending", {
                    url: "/Pending",
                    templateUrl: "/AppJs/advanced/institutions/views/summary/_pending.html",
                    controller: "AdvInstitutionDetailPendingController",
                    data: {
                        displayName: "Pending",
                        title: "Institution Details - Pending"
                    }
                })
                .state("root.adv.institutions.print", {
                    url: "/print",
                    templateUrl: "AppJs/advanced/institutions/views/_print.html",
                    controller: "AdvInstitutionsPrintController",
                    data: {
                        displayName: "List",
                        title: "Institutions - Results"
                    }
                })

                .state("root.adv.institutions.ceases", {
                    url: "/ceases",
                    templateUrl: "AppJs/advanced/institutions/views/tophold_ceases.html",
                    controller: "AdvInstitutionsTHCAdminController",
                    data: {
                        displayName: "Tophold Ceases",
                        title: "Tophold Ceases"
                    },
                    reload: true

                })

                .state("root.adv.institutions.thcacquire", {
                    url: "/thcacquire",
                    templateUrl: "AppJs/advanced/institutions/views/tophold_acquired.html",
                    controller: "AdvInstitutionsTHCAdminController",
                    data: {
                        displayName: "Tophold Acquired by Tophold",
                        title: "Tophold Acquired by Tophold"
                    },
                    reload: true

                })


                // ADVANCED -- MARKETS
                .state("root.adv.markets", {
                    url: "/markets",
                    templateUrl: "AppJs/advanced/markets/index.html",
                    controller: "AdvMarketsController",
                    data: {
                        displayName: "Markets"
                    }
                })
                .state("root.adv.markets.recode", {
                    url: "/recode",
                    templateUrl: "AppJs/advanced/markets/views/_recodeByState.html",
                    controller: "AdvMarketRecodeController",
                    data: {
                        displayName: "Recode",
                        title: "Markets - Recode"
                    }
                })
                .state("root.adv.markets.search", {
                    url: "/search",
                    templateUrl: "AppJs/advanced/markets/views/_search.html",
                    controller: "AdvMarketSearchController",
                    data: {
                        displayName: "Search",
                        title: "Markets - Search"
                    },
                    reload: true
                })
                .state("root.adv.markets.browse", {
                    url: "/browse",
                    templateUrl: "AppJs/advanced/markets/views/_browse.html",
                    controller: "AdvMarketBrowseController",
                    data: {
                        displayName: "Browse",
                        title: "Markets - Browse"
                    }
                })
                .state("root.adv.markets.CustomMarkets", {
                    url: "/CustomMarkets",
                    templateUrl: "AppJs/advanced/markets/views/_customMarket.html",
                    controller: "advCustomMarketController",
                    data: {
                        displayName: "Custom Markets",
                        title: "Custom Markets"
                    },
                    reload: true
                })
                .state("root.adv.markets.CustomMarketDetails", {
                    url: "/customMarketDetails/:marketId",
                    templateUrl: "AppJs/advanced/markets/views/customMarketDetails.html",
                    controller: "advCustomMarketDetailsController",
                    data: {
                        displayName: "Custom Markets Details",
                        title: "Custom Markets Details"
                    },
                    reload: true
                })

                .state("root.adv.markets.browsecounties", {
                    url: "/browse/:state",
                    templateUrl: "AppJs/advanced/markets/views/_browse.counties.html",
                    controller: "AdvMarketBrowseCountiesController",
                    data: {
                        displayName: "Browse <strong>{{state}}</strong> Counties",
                        title: "Markets - Browse Counties"
                    },
                    resolve: {
                        state: ['$stateParams', function ($stateParams) {
                            return $stateParams.state;
                        }]
                    }
                })
                .state("root.adv.markets.list", {
                    url: "/list?rssd&fdic&name&marketnumber&zip&state&city&county&international",
                    templateUrl: "AppJs/advanced/markets/views/_list.html",
                    controller: "AdvMarketListController",
                    data: {
                        displayName: "List",
                        title: "Markets - Results"
                    },
                    reload: true
                })

               .state("root.adv.markets.hhidepositanalysisreport", {
                   url: "/hhidepositanalysisreport/:marketId",
                   templateUrl: "AppJs/advanced/markets/views/HHIDepositAnalysisReport.html",
                   controller: "advMarketHHIDepositAnaysisController",
                   data: {
                       displayName: "HHI Deposit Analysis Report",
                       title: "HHI Deposit Analysis Report"
                   },
                   reload: true
               })

                .state("root.adv.markets.detail", {
                    abstract: true,
                    url: "/:market",
                    templateUrl: "/AppJs/advanced/markets/views/_detail.html",
                    controller: "AdvMarketDetailController",
                    data: {
                        breadcrumbProxy: "root.adv.markets.detail.definition"
                    }
                })
                .state("root.adv.markets.detail.definition", {
                    url: "/definition",
                    templateUrl: "/AppJs/advanced/markets/views/details/_definition.html",
                    controller: "AdvMarketDetailDefinitionController",
                    data: {
                        displayName: "Details",
                        title: "Market Details"
                    }
                })
                .state("root.adv.markets.detail.hhi", {
                    url: "/hhi",
                    templateUrl: "/AppJs/advanced/markets/views/details/_hhi.html",
                    controller: "AdvMarketDetailHhiController",
                    data: {
                        displayName: "HHI",
                        title: "Market HHI"
                    }
                })
                .state("root.adv.markets.detail.map", {
                    url: "/map",
                    templateUrl: "/AppJs/advanced/markets/views/details/_map.html",
                    controller: "AdvMarketDetailMapController",
                    data: {
                        displayName: "Map",
                        title: "Market Map"
                    }
                })
                .state("root.adv.markets.detail.history", {
                    url: "/history",
                    templateUrl: "/AppJs/advanced/markets/views/details/_history.html",
                    controller: "AdvMarketDetailHistoryController",
                    data: {
                        displayName: "History",
                        title: "Market History"
                    }
                })
                .state("root.adv.markets.detail.pending", {
                    url: "/pending",
                    templateUrl: "/AppJs/advanced/markets/views/details/_pending.html",
                    controller: "AdvMarketDetailPendingController",
                    data: {
                        displayName: "Pending",
                        title: "Market Pending"
                    }
                })
                .state("root.adv.markets.listByState", {
                    abstract: true,
                    url: "/list-by",
                    templateUrl: "AppJs/advanced/markets/views/_listByState.html",
                    controller: "AdvMarketsByStateController"
                })
                .state("root.adv.markets.listByState.andDistrict", {
                    url: "/state-and-district",
                    templateUrl: "AppJs/advanced/markets/views/listByState/andDistrict.html",
                    data: {
                        displayName: "By State and District",
                        title: "Markets - By State and District",
                        h1: "and District"
                    }
                })
                .state("root.adv.markets.listByState.andCounty", {
                    url: "/state-and-county",
                    templateUrl: "AppJs/advanced/markets/views/listByState/andCounty.html",
                    data: {
                        displayName: "By State and County",
                        title: "Markets - By State and County",
                        h1: "and County"
                    }
                })
                .state("root.adv.markets.listByState.andMarket", {
                    url: "/state-and-market",
                    templateUrl: "AppJs/advanced/markets/views/listByState/andMarket.html",
                    data: {
                        displayName: "By State and Market",
                        title: "Markets - By State and Market Number",
                        h1: "and Market Number"
                    }
                })
                .state("root.adv.markets.analysis", {
                    url: "/marketOverlap",
                    templateUrl: "AppJs/advanced/markets/views/analysis/_commonMarkets.html",
                    controller: "advCommonMarketsController",
                    data: {
                        displayName: "Banking Market Overlap",
                        title: "Banking Market Overlap"
                    }
                })
                // ADVANCED -- HHI ANALYSIS
                .state("root.adv.hhi-analysis", {
                    url: "/hhi-analysis",
                    templateUrl: "AppJs/advanced/hhi-analysis/index.html",
                    controller: "AdvHhiAnalysisController",
                    data: {
                        displayName: "HHI Analysis"
                    }
                })

                 //ADVANCED -- HISTORY
                .state("root.adv.history", {
                    url: "/history",
                    templateUrl: "AppJs/advanced/history/index.html",
                    controller: "HistoryController",
                    data: {
                        displayName: "Institution History"
                    }
                })
                .state("root.adv.history.institutions", {
                    url: "/institutions",
                    templateUrl: "AppJs/advanced/history/views/institutions.html",
                    controller: "AdvHistoryInstitutionSearch",
                    params: { transferCriteria: null },
                    data: {
                        displayName: "Search Institutions"                        
                    },
                    resolve: {
                        transferCriteria: ['$stateParams', function ($stateParams) {
                            return $stateParams.transferCriteria;
                        }]
                    }                    
                })
               .state("root.adv.history.markets", {
                   url: "/markets",
                   templateUrl: "AppJs/advanced/history/views/_marketHistorySearch.html",
                   controller: "AdvHistoryMarketSearch",
                   data: {
                       displayName: "Search Markets"
                   },
               })
                .state("root.adv.history.byDate", {
                    url: "/by-date",
                    templateUrl: "AppJs/advanced/history/views/bydate.html",
                    data: {
                        displayName: "Search by Date"
                    }
                })
                 .state("root.adv.history.add", {
                     url: "/add",
                     templateUrl: "AppJs/advanced/history/views/addHistoryTransaction.html",
                     controller: "AdvAddHistoryTransactionController",
                     data: {
                         displayName: "Add History Record"
                     }
                 })
                .state("root.adv.history.insthistory", {
                    url: "/insthistory/:rssdId",
                    templateUrl: "AppJs/advanced/history/views/summary/_instHistory.html",
                    controller: "AdvInstitutionsHistoryController",
                    data: {
                        displayName: "Institution History"
                    },
                })
                .state("root.adv.history.structureAdjusted", {
                    url: "/structureAdjusted/:rssd",
                    templateUrl: "AppJs/advanced/history/views/summary/_structureAdjustedReport.html",
                    controller: "AdvStructureAdjustedHistoryReportController",
                    data: {
                        displayName: "Structure - Adjusted History Report"
                    },
                })
                .state("root.adv.history.markethistory", {
                    url: "/markethistory/:market",
                    templateUrl: "AppJs/advanced/history/views/summary/_marketHistory.html",
                    controller: "AdvMarketHistoryController",
                    data: {
                        displayName: "Market History"
                    },
                })
                // ADVANCED -- PENDING TRANSACTIONS
                .state("root.adv.pending", {
                    url: "/pending-transactions",
                    templateUrl: "AppJs/advanced/pending/index.html",
                    controller: "PendingTxnsController",
                    data: {
                        displayName: "Pending Transactions"
                    },
                    reload: true
                })
                .state("root.adv.pending.edit", {
                    url: "/pending-transactions/edit/:pendingTxnId",
                    templateUrl: "/AppJs/advanced/pending/views/addPending.html",
                    controller: "PendingTxnsAddController",
                    data: {
                        displayName: "Add/Edit Pending Transactions"
                    },
                    reload: true
                })
                .state("root.adv.pending.add", {
                    url: "/pending-transactions/add",
                    templateUrl: "/AppJs/advanced/pending/views/addPending.html",
                    controller: "PendingTxnsAddController",
                    data: {
                        displayName: "Add/Edit Pending Transactions"
                    },
                    reload: true
                })
                // ADVANCED -- REPORTS
                .state("root.adv.reports", {
                    url: "/reports",
                    templateUrl: "AppJs/advanced/reports/index.html",
                    controller: "AdvReportsController",
                    data: {
                        displayName: "Reports"
                    }
                })
                // ADVANCED -- ADMINISTRATION
                .state("root.adv.admin", {
                    url: "/admin",
                    templateUrl: "AppJs/advanced/admin/index.html",
                    controller: "AdminController",
                    data: {
                        displayName: "Administration"
                    }
                })
                //.state("root.adv.admin.demo", {
                //    url: "/demo",
                //    templateUrl: "AppJs/advanced/admin/views/demo.html",
                //    //controller: "AdminUsersController",
                //    data: {
                //        displayName: "Demo"
                //    }
                //})
                .state("root.adv.admin.users", {
                    url: "/users",
                    templateUrl: "AppJs/advanced/admin/views/users.html",
                    controller: "AdminUsersController",
                    data: {
                        displayName: "Users"
                    }
				})
				.state("root.adv.quarterlydata", {
					url: "/quarterlyData",
					templateUrl: "AppJs/advanced/admin/views/quarterlyDataChecksIndex.html",
					controller: "QuarterlyDataChecksController",
					data: {
						displayName: "Quarterly Data Admin"
					}
				})		

				.state("root.adv.quarterlydata.lqdata", {
					url: "/lqvals",
					templateUrl: "AppJs/advanced/admin/views/lqValsUpdate.html",
					controller: "LQValsUpdateController",
					data: {
						displayName: "Last Quarter Financials Update"
					}
				})				


				.state("root.adv.quarterlydata.rolemembers", {
					url: "/rolemembers",
					templateUrl: "AppJs/advanced/admin/views/roleMembers.html",
					controller: "RoleMemberRptController",
					data: {
						displayName: "Role Members Report"
					}
				})
                .state("root.adv.admin.sitecontent", {
                    url: "/sitecontent",
                    templateUrl: "AppJs/advanced/admin/views/sitecontent.html",
                    controller: "SiteContentController",
                    data: {
                        displayName: "Site Content"
                    }
                })
                .state("root.adv.admin.news", {
                    url: "/news",
                    templateUrl: "AppJs/advanced/admin/views/news.html",
                    controller: "NewsController",
                    data: {
                        displayName: "News"
                    }
                })
                .state("root.adv.admin.HHIValidation", {
                    url: "/HHIValidation",
                    templateUrl: "AppJs/advanced/admin/views/HHIScenarioValidation.html",
                    controller: "HHIScenarioValidationController",
                    data: {
                        displayName: "HHIValidation"
                    }
                })
                .state("root.adv.admin.geoCodeBulkUpload", {
                    url: "/geoCodeBulkUpload",
                    templateUrl: "AppJs/advanced/admin/views/geoCodeBulkUpload.html",
                    controller: "geoCodeBulkUploadController",
                    data: {
                        displayName: "Batch Upload"
                    }
                })
                .state("root.adv.admin.reportGenerator", {
                    url: "/reportGenerator",
                    templateUrl: "AppJs/advanced/admin/views/reportGenerator.html",
                    controller: "AdminReportGeneratorController",
                    data: {
                        displayName: "Report Generator"
                    }
                })
                .state("root.adv.admin.lqValsUpdate", {
                    url: "/lqvalsUpdate",
                    templateUrl: "AppJs/advanced/admin/views/lqValsUpdate.html",
                    controller: "LQValsUpdateController",
                    data: {
                        displayName: "Last Quarter Financials Update"
                    }
                })

                .state("root.adv.admin.uniZeroUpdate", {
                    url: "/uniZeroUpdate",
                    templateUrl: "AppJs/advanced/admin/views/uniZeroUpdate.html",
                    controller: "UniZeroUpdateController",
                    data: {
                        displayName: "Uninumber Zero Updates"
                    }
                })

                .state("root.adv.admin.missedBrClosings", {
                    url: "/missedBrClosings",
                    templateUrl: "AppJs/advanced/admin/views/missedBrClosings.html",
                    controller: "MissedBrClosingsController",
                    data: {
                        displayName: "Missed Branch Closings"
                    }
                })
				.state("root.adv.admin.validateinsttype", {
					url: "/validateInstType",
					templateUrl: "AppJs/advanced/admin/views/validateInstEntityType.html",
					controller: "ValidateInstTypeController",
					data: {
						displayName: "Validate Institution Entity Types"
					}
				})

				
                //.state("root.adv.admin.lqValsUpdate", {
                //    url: "/lqvalsUpdate",
                //    templateUrl: "AppJs/advanced/admin/views/lqValsUpdate.html",
                //    controller: "LQValsUpdateController",
                //    data: {
                //        displayName: "Last Quarter Financials Update"
                //    }
                //})
                // ADVANCED -- HELP
                .state("root.adv.help", {
                    url: "/help",
                    templateUrl: "AppJs/advanced/help/index.html",
                    controller: "AdvHelpController",
                    data: {
                        requiresDisclaimer: false,
                        displayName: "Help"
                    }
                })
        }]);
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('AnalysisWizard', AnalysisWizard);

    AnalysisWizard.$inject = ['UserData'];

    function AnalysisWizard(UserData) {
        var service = {
            getData: getData
        };

        return service;
        ////////////////

        function getData() {

        }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('PublicCommonMarketsController', PublicCommonMarketsController);

    PublicCommonMarketsController.$inject = ['$scope', '$stateParams', 'AnalysisService', 'InstitutionsService', 'UserData', '$window', 'leafletData', 'leafletBoundsHelpers', 'MarketsService', 'MarketMapService'];

    function PublicCommonMarketsController($scope, $stateParams, AnalysisService, InstitutionsService, UserData, $window, leafletData, leafletBoundsHelpers,MarketsService, MarketMapService) {
        angular.extend($scope, {
            data: [],
            dataReady: false,
            hasInvalidParams: false,
            buyer: $stateParams.buyer,
            targets: $stateParams.targets,
            branches: $stateParams.branches,
            marketIds:[]
        });

        var year = (new Date()).getFullYear();
        var mapBoxAndOpenMapsAttribution = '&copy;' + year + ' <a href="https://www.mapbox.com/about/maps/">MapBox</a> &copy;' + year + ' <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>';

        $scope.UserData = UserData;
        $scope.selectAll = false;
        $scope.selectAllExceeds = false;
        $scope.exceedsMarketCount = 0;
        $scope.mapReady = false;
        $scope.showMap = false;
        $scope.center = [0, 0];
        $scope.tiles = {};
        $scope.defaults = {};
        $scope.map = null;
        $scope.geoJson = null;
        $scope.bounds = null;
        $scope.markers = [];
        $scope.layers = { overlays: {} };
        $scope.buyerMarkers = [];
        $scope.targetMarkers = [];
        $scope.otherMarkers = [];
        $scope.buyerMarker
        $scope.mapToggles = { buyers: true, targets: true, others: true };

        $scope.mapStyles = {
            "CountiesRoadsCities": {
                name: 'Counties, Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdk0r3001uganjch20akrs',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: true,
                        roads: true,
                            cities: true
                }
            },
            "Counties": {
                name: 'Counties Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhoaj50020ganjjg9cvcxi',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: true,
                        roads: false,
                            cities: false
                }
            },
            "Roads": {
                name: 'Roads Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhlhll001wg7ncl1gps309',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: false,
                        roads: true,
                            cities: false
                }
            },
            "Cities": {
                name: 'Cities Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdkdbp001gg8m4xzloqdl5',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: false,
                        roads: false,
                            cities: true
                }
            },
            "CountiesRoads": {
                name: 'Counties & Roads',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhsd0o001xg7nc6tkcbv4y',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: true,
                        roads: true,
                            cities: false
                }
            },
            "RoadsCities": {
                name: 'Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circddako001tganj2eqgiaph',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: false,
                        roads: true,
                            cities: true
                }
            },
            "CountiesCities": {
                name: 'Counties & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhhjbj001igfkvz8hqfkxe',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: true,
                        roads: false,
                            cities: true
                }
            },
            "None": {
                name: 'None',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                        options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'cirqcpxde002pg9nggrktu888',
                            attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                    data: {
                    counties: false,
                        roads: false,
                            cities: false
                }
            }
        }

        $scope.closeMap = function () {
            $scope.showMap = false;
        }


        $scope.toggleMapMarkers = function (markerTypeName) {
            switch (markerTypeName) {
                case "buyers":
                    $scope.mapToggles.buyers = !$scope.mapToggles.buyers;
                    break;
                case "targets":
                    $scope.mapToggles.targets = !$scope.mapToggles.targets;
                    break;
                case "others":
                    $scope.mapToggles.others = !$scope.mapToggles.others;
                    break;
                default:
                    return;
            }

            $scope.markers = [];
            if ($scope.mapToggles.buyers) {
                $scope.markers = $scope.markers.concat($scope.buyerMarkers);
            }
            if ($scope.mapToggles.targets) {
                $scope.markers = $scope.markers.concat($scope.targetMarkers);
            }
            if ($scope.mapToggles.others) {
                $scope.markers = $scope.markers.concat($scope.otherMarkers);
            }
        }

        $scope.setMapStyle = function () {
            $scope.tiles = {
                name: 'Counties, Roads & Cities',
                url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                options: {
                    apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                    mapid: 'circdk0r3001uganjch20akrs',
                    attribution: mapBoxAndOpenMapsAttribution
                },
                type: 'xyz',
                data: {
                    counties: true,
                    roads: true,
                    cities: true
                }
            }
        }

        $scope.activateMap = function (marketId) {          
            $scope.loadMap(marketId).then(function (result) {
                $scope.map = result.map;

                $scope.$on("leafletDirectiveGeoJson.leafy.mouseover",
                    function (ev, leafletPayload) {

                        var layer = leafletPayload.leafletEvent.target,
                        feature = leafletPayload.leafletObject.feature;

                        layer.setStyle({
                            weight: 4,
                            color: "#000",
                            fillOpacity: 0.75
                        });
                        layer.bringToFront();

                        $scope.hoveredMarket = feature.properties;
                    });          

                var bounds = null;
                if ($scope.map.geoJson) {
                    bounds = leafletBoundsHelpers.createBoundsFromArray([
                        [$scope.map.geoJson.bbox[1], $scope.map.geoJson.bbox[0]],
                        [$scope.map.geoJson.bbox[3], $scope.map.geoJson.bbox[2]]
                    ]);
                    delete $scope.map.geoJson.bbox;
                }
                $scope.bounds = bounds;
                $scope.center = {};

                $scope.layers.overlays.market = {
                    name: "theMarket",
                    type: "geoJSONShape",
                    data: $scope.map.geoJson,
                    layerOptions: {
                        style: {
                            //fillColor: result.map.color || "#577492",
                            fillColor: "#CCCCCC",
                            weight: 2,
                            opacity:.35,
                            color: 'white',
                            dashArray: '3',
                            fillOpacity: 0.5
                        }
                    },
                    visible: true,
                    layerParams: {
                        showOnSelector: false,
                    }
                };

                $scope.marketUndefined = $scope.map.geoJson == null;
                $scope.isMapShapeCurrent = $scope.map.isMapShapeCurrent;
                    $scope.mapReady = true;
            })
        }

        $scope.loadMap = function (marketId) {
            $scope.mappedMarketId = marketId;

            MarketsService.get(marketId, false, false, true, false).then(
                function (result) {
                    $scope.map = result.map;

                    var bounds = null;
                    if ($scope.map.geoJson) {
                        bounds = leafletBoundsHelpers.createBoundsFromArray([
                            [$scope.map.geoJson.bbox[1], $scope.map.geoJson.bbox[0]],
                            [$scope.map.geoJson.bbox[3], $scope.map.geoJson.bbox[2]]
                        ]);
                        delete $scope.map.geoJson.bbox;
                    }
                    $scope.bounds = bounds;
                    $scope.center = {};

                    $scope.layers.overlays.market = {
                        name: "theMarket",
                        type: "geoJSONShape",
                        data: $scope.map.geoJson,
                        layerOptions: {
                            style: {
                                //fillColor: result.map.color || "#577492",
                                fillColor: "#CCCCCC",
                                weight: 2,
                                opacity: .35,
                                color: 'white',
                                dashArray: '3',
                                fillOpacity: 0.5
                            }
                        },
                        visible: true,
                        layerParams: {
                            showOnSelector: false,
                        }
                    };

                    var targets = $scope.targets;
                    var branches = $scope.branches;
                    var buyer = $scope.buyer;

                    $scope.getProformaBranches(marketId, buyer, targets, branches)

                    $scope.marketUndefined = $scope.map.geoJson == null;
                    $scope.isMapShapeCurrent = $scope.map.isMapShapeCurrent;
                    $scope.mapReady = true;
                    $scope.showMap = true;
                }
            );
        }

        $scope.getProformaBranches = function(marketId, buyer, targets, branches) {
            var blueIcon = {
                iconUrl: '/Content/leaflet/images/marker-icon-outline-blue.png',
                iconSize: [18, 28],
                iconAnchor: [25, 41],
                popupAnchor: [-3, -76],
                //shadowUrl: '/Content/leaflet/images/marker-shadow.png',
                shadowSize: [12, 20],
                shadowAnchor: [25, 41],
                class: "other"
            };

            var redIcon = {
                iconUrl: '/Content/leaflet/images/marker-icon-red-square.png',
                iconSize: [18, 28],
                iconAnchor: [25, 41],
                popupAnchor: [-3, -76],
                //shadowUrl: '/Content/leaflet/images/marker-shadow.png',
                shadowSize: [41, 41],
                shadowAnchor: [25, 41],
                class: "buyer"
            };

            var greenIcon = {
                iconUrl: '/Content/leaflet/images/marker-icon-green.png',
                iconSize: [18, 28],
                iconAnchor: [25, 41],
                popupAnchor: [-3, -76],
                //shadowUrl: '/Content/leaflet/images/marker-shadow.png',
                shadowSize: [41, 41],
                shadowAnchor: [25, 41],
                class: "target"
            };

            MarketsService.getProformaLocations(marketId, buyer, targets, branches).then(
                function (branchLocations) {
                    // add buyer branch markers                   
                    if (branchLocations.buyerBranchLocations && branchLocations.buyerBranchLocations.length) {
                        for (var i = 0; i < branchLocations.buyerBranchLocations.length; i++) {
                            //$scope.markers.push()
                            $scope.buyerMarkers.push(
                            {
                                lat: branchLocations.buyerBranchLocations[i].lat,
                                lng: branchLocations.buyerBranchLocations[i].lng,
                                icon: redIcon,
                                title: 'Buyer Branch Icon'
                            });
                        }
                    }

                    // add target branch markers
                    if (branchLocations.targetBranches && branchLocations.targetBranches.length) {
                        for (var i = 0; i < branchLocations.targetBranches.length; i++) {
                            //$scope.markers.push(
                            $scope.targetMarkers.push(
                                {
                                    lat: branchLocations.targetBranches[i].lat,
                                    lng: branchLocations.targetBranches[i].lng,
                                    icon: greenIcon,
                                    title: 'Target Branch Icon'
                                });
                        }
                    }

                    // add other/non-purchase branch markers
                    if (branchLocations.otherBranches && branchLocations.otherBranches.length) {
                        for (var i = 0; i < branchLocations.otherBranches.length; i++) {
                            //$scope.markers.push(
                            $scope.otherMarkers.push(
                                {
                                    lat: branchLocations.otherBranches[i].lat,
                                    lng: branchLocations.otherBranches[i].lng,
                                    icon: blueIcon,
                                    title: 'Other Branches Icon'
                                });
                        }
                    }

                    $scope.markers = $scope.buyerMarkers.concat($scope.targetMarkers, $scope.otherMarkers);
                }
             )
        }
 
        $scope.selectOverlapExceed = function () {
            for (var i = 0; i < $scope.data.markets.length; i++) {
                if ($scope.data.markets[i].exceedsAuthority) {
                    var mrk = { marketId: $scope.data.markets[i].market.marketId, marketName: $scope.data.markets[i].market.name };
                    //add to the side
                    if (!$scope.selectAllExceeds) {
                        UserData.markets.save(mrk);
                    }
                    else {
                        UserData.markets.remove(mrk.marketId);
                    }
                }

            }
            $scope.selectAllExceeds = !$scope.selectAllExceeds;
        }
        $scope.addedMarket = function (marketId) {
            if (_.indexOf($scope.marketIds, marketId) > -1) { // is currently selected
                var idx = _.indexOf($scope.marketIds, marketId);
                $scope.marketIds.splice(idx, 1);
            } else { // is newly selected
                $scope.marketIds.push(marketId);
            }
        };
        $scope.runProFormaSelectedMarkets = function () {
            var buyer = $scope.buyer;
            var targets = $scope.targets;
            var marketNum = _.join(_.flatMap($scope.marketIds), ",");


            $window.open('/report/proformacommonmarket?markets=' + marketNum + '&buyer=' + $stateParams.buyer + '&target=' + $stateParams.targets, '_blank');
            toastr.success("Report generated and ran in a new window.");
        };
        $scope.selectOverlap = function () {
            for (var i = 0; i < $scope.data.markets.length; i++) {
                var mrk = { marketId: $scope.data.markets[i].market.marketId, marketName: $scope.data.markets[i].market.name };
                //add to the side
                if (!$scope.selectAll)
                {
                    UserData.markets.save(mrk);
                }
                else
                {
                    UserData.markets.remove(mrk.marketId);
                }
            }
            $scope.selectAll = !$scope.selectAll;
        }
               

        activate();

        function activate() {
            $scope.setMapStyle();

            if (!$stateParams.buyer || (!$stateParams.targets && !$stateParams.branches)) {
                $scope.hasInvalidParams = true;
                return;
            }

            var branchData = ($stateParams.branches == null || ($stateParams.branches.length ?? 0) == 0) ? "" : $stateParams.branches;

            AnalysisService
                .getCommonMarkets($stateParams.buyer, $stateParams.targets == null ? "" : $stateParams.targets, branchData)
                .then(function (result) {
                    $scope.data = result;
                    $scope.buyerDistrictContact = result.buyerDistrictContact;
                    $scope.dataReady = true;
                    if (!result.commonStates.errorFlag)
                        $scope.commonStates = result.commonStates.resultObject;
                    else
                        toastr.error($scope.commonStates.messageTextItems[0]);
                    
                    for (var i = 0; i < $scope.data.markets.length; i++) {
                        if ($scope.data.markets[i].exceedsAuthority) {
                            $scope.exceedsMarketCount++;
                        }
                    }
                   
                    
                });            
        }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('PublicHhiAnalysisController', PublicHhiAnalysisController);

    PublicHhiAnalysisController.$inject = ['$rootScope', '$scope', '$state', 'toastr', 'AnalysisWizard'];

    function PublicHhiAnalysisController($rootScope, $scope, $state, toastr, AnalysisWiz) {
        angular.extend($scope, {
            isIndex: isOnIndexPage($state.current),
            startMarketsWiz: function () {
                $state.go('root.markets')
                    .then(function () {
                        toastr.error('Markets What-If Wizard not implemented yet');
                    });
            },
            startInstitutionsWiz: function () {
                //alert('int wiz');
                $state.go('root.institutions')
                    .then(function () {
                        toastr.error('Institutions What-If Wizard not implemented yet');
                    });
            }
        });

        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.isIndex = isOnIndexPage(toState);
            });
        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.analysis";
        }

    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('errorcontroller', errorcontroller);

    errorcontroller.$inject = ['$rootScope', '$scope', '$state'];

    function errorcontroller($rootScope, $scope, $state) {
        angular.extend($scope, {
            isIndex: isOnIndexPage($state.current),
            //subTitle: getSubTitle($state.current),
        });

        activate();

        function activate() {
            
        }

        
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('PublicIndexController', PublicIndexController);

    PublicIndexController.$inject = ['$scope', '$uibModal', 'AdvancedNewsService'];

    function PublicIndexController($scope, $uibModal, News) {
        $scope.title = "Welcome to CASSIDI<small>&reg;</small>";
        $scope.expandonymData = [
            { showCap: true, word: "Competitive" },
            { showCap: true, word: "Analysis" },
            { showCap: false, word: "and" },
            { showCap: true, word: "Structure" },
            { showCap: true, word: "Source" },
            { showCap: true, word: "Instrument" },
            { showCap: false, word: "for" },
            { showCap: true, word: "Depository" },
            { showCap: true, word: "Institutions" }
        ];
        $scope.expanded = true;
        $scope.contentReady = false;

        $scope.expandonymClick = function () {
            $scope.expanded = !$scope.expanded;
        };


        var defaultNewsScrollInterval = 5000;
        $scope.newsScrollInternval = defaultNewsScrollInterval;

        var dismissedIds = News.getDismissedNewsIds();
        $scope.news = [];


        $scope.hasNews = function () {
            return _.filter($scope.news, function (item) { return !item.dismissed; }).length > 0;
        };

        $scope.showNews = function (newsItem) {
            var modalInstance = $uibModal.open({
                templateUrl: 'AppJs/public/views/newsModalTemplate.html',
                controller: 'NewsModalController',
                size: 'lg',
                windowClass: 'cassidi-standard-modal news',
                resolve: {
                    item: function () {
                        return newsItem;
                    }
                }
            });
        };

        $scope.setNewsScrolling = function (isScrolling) {
            if (isScrolling)
            {
                $scope.newsScrollInternval = defaultNewsScrollInterval;
            }
            else { $scope.newsScrollInternval = false; }
        }

        activate();

        function activate() {


            News.query("WELCOME_PUBLIC", 1).then(function (result) {
				if (result && result.length > 0) {
					$scope.content = News.format(result[0].body);
				}
            });


            News.query("PUBLIC_NEWS", 6).then(function (result) {
                $scope.contentReady = true;
                $scope.news = _.filter(result, function (item) { return _.indexOf(dismissedIds, item.newsId) == -1; });
            });


        }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionBrowseController', InstitutionBrowseController);

    InstitutionBrowseController.$inject = ['$scope', '$state', 'StatesService'];

    function InstitutionBrowseController($scope, $state, StatesService) {

        $scope.hasState = false;
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionBrowseCountiesController', InstitutionBrowseCountiesController);

    InstitutionBrowseCountiesController.$inject = ['$scope', '$state', '$stateParams', 'StatesService'];

    function InstitutionBrowseCountiesController($scope, $state, $stateParams, StatesService) {
        if (!$stateParams.state) {
            $state.go("^");
            return;
        }

        $scope.hasState = true;
        $scope.stateName = $stateParams.state;
        $scope.stateId = 0;
        $scope.counties = [];
        $scope.countiesReady = false;

        activate();

        function activate() {
            StatesService.statesPromise.then(function (result) {
                var states = result,
                    state = _.find(states, { state: $stateParams.state });

                $scope.stateId = state.stateId;
                $scope.counties = state.counties;
                $scope.countiesReady = true;
            });
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionCommonMarketsController', InstitutionCommonMarketsController);

    InstitutionCommonMarketsController.$inject = ['$scope', '$stateParams', 'InstitutionsService', 'UserData'];

    function InstitutionCommonMarketsController($scope, $stateParams, InstitutionsService, UserData) {
        $scope.UserData = UserData;
        $scope.selectAll = false;
        $scope.selectAllExceeds = false;
        $scope.buyer = $stateParams.buyer;
        $scope.target = $stateParams.target;
        $scope.markets = [];
        $scope.marketIds = [];
        //for multiple proforma report link
       
               
       
        $scope.saveMarket = function (market) {
            var id = market.marketId;
            if (!$scope.isSavedMarket(id)) {

                var mrk = { marketId: market.marketId, marketName: market.name};
                $scope.markets.push(mrk);
                $scope.marketIds.push(market.marketId);
                $scope.strMarketIds = $scope.marketIds.join();
            }
        }
        $scope.isSavedMarket = function (id) {
            var mId = "";
            if (id.marketId == null) {
                mId = id;
            }
            else {
                mId = id.marketId;
            }
            return _.findIndex($scope.markets, { marketId: mId }) > -1;
        };
        $scope.removeMarket = function (market) {
            _.remove($scope.markets, { marketId: market.marketId });
            _.remove($scope.marketIds, market.marketId);
            $scope.strMarketIds = $scope.marketIds.join();
        };
        $scope.toggleMarket = function (market) {
            var id = market.marketId;
            if ($scope.isSavedMarket(id))
                $scope.removeMarket(market);
            else
                $scope.saveMarket(market);
        };
        
        $scope.selectOverlapExceed = function () {
            for (var i = 0; i < $scope.pfSummaries.ppSummaries.length; i++) {
                if ($scope.pfSummaries.ppSummaries[i].exceedsAuthority) {
                    var mrk = { marketId: $scope.pfSummaries.ppSummaries[i].market.marketId, marketName: $scope.pfSummaries.ppSummaries[i].market.name };
                    $scope.markets.push(mrk);
                   
                }
                
            }
            $scope.selectAllExceeds = !$scope.selectAllExceeds;
        }

        $scope.selectOverlap = function () {
            for (var i=0; i< $scope.pfSummaries.ppSummaries.length; i++)
            {
                var mrk = { marketId:$scope.pfSummaries.ppSummaries[i].market.marketId, marketName: $scope.pfSummaries.ppSummaries[i].market.name };
                $scope.markets.push(mrk);
            }
            $scope.selectAll = !$scope.selectAll;
        }

        $scope.saveMarkets = function () {
            for (var i = 0; i < $scope.markets.length; i++) {
                UserData.markets.save($scope.markets[i]);
            }
        }

        activate();
        function activate() {
            var params = {
                buyer: $stateParams.buyer,
                target: $stateParams.target
            }
            InstitutionsService.getCommonMarkets({ buyer: $stateParams.buyer, target: $stateParams.target }).then(function (result) {
                $scope.pfSummaries = result;
                $scope.pfSummariesLoaded = true;
            });
        }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionListController', InstitutionListController)

    InstitutionListController.$inject = ['$scope', '$state', '$stateParams', '$location', 'InstitutionsService', 'UserData', 'ProFormaService', 'StatesService', '$window', '$timeout'];

    function InstitutionListController($scope, $state, $stateParams, $location, InstitutionsService, UserData, ProFormaService, StatesService, $window, $timeout) {
        $scope.instData = [];
        $scope.instDataReady = false;
        $scope.instPageSize = 30;
        $scope.searchState = 'initial';

        $scope.scrollLoadDefaultCount = 30;
        $scope.scrollLoadBatchSize = 10;
        $scope.scrollLoadCount = $scope.scrollLoadDefaultCount;
        $scope.totalInstCount = 0;
        $scope.showMoreLinkVisible = false;

        $scope.viewCommonMarkets = function () {
            var ids = [];
            for (var i = 0; i < $scope.targetRSSD.length; i++) {
                ids.push($scope.targetRSSD[i].rssdId);
            }
            var data = {
                buyer: $scope.buyerRSSD[0].rssdId,
                target: ids.join()
            }

            $state.go('^.commonmarkets', data);
        }

        $scope.getTargetBuyer = function () {
            return ProFormaService.selections.buyer;
        };

        $scope.getTargetList = function () {
            return ProFormaService.selections.targets;
        };

        // Need to get user friendly names from Ids
        $scope.state = $stateParams.state;
        $scope.name = $stateParams.name;
        $scope.city = $stateParams.city,
        $scope.county = $stateParams.county;
        $scope.zip = $stateParams.zip;

        $scope.removeCriteria = function (criterionName) {
            delete $scope.criteria[criterionName];
            var search = $location.search();
            delete search[criterionName];
            $location.search(search);

            if (_.isEmpty($scope.criteria))
                $state.go("^");
            else
                setSearchResults();
        }


        $scope.resetLoadMoreCounter = function () { $scope.scrollLoadCount = $scope.scrollLoadDefaultCount; };

        $scope.loadMoreOnWindowScroll = function (ignoreWindowPosition) {
            $scope.$apply(function () {
                if (($scope.scrollLoadCount < $scope.totalInstCount) && ($(window).scrollTop() > $(document).height() - $(window).height() - 325)) {
                    $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                    $scope.searchState = 'scrollLoading';
                }
            });
        }

        $scope.loadMoreOnLinkClick = function () {
            if ($scope.scrollLoadCount < $scope.totalInstCount) {
                $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                $scope.searchState = 'scrollLoading';
            }
        }

        $scope.onLoadMoreComplete = function () {
            $scope.clearLoadingMoreMsg();
        }

        $scope.clearLoadingMoreMsg = function () {
            $timeout(function () { $scope.searchState = 'loaded'; }, 3000);
        }

        activate();

        function activate() {

            //ProFormaService.selections.load();
            ProFormaService.clearBuyer();
            ProFormaService.clearTargets();

            setSearchResults();
            setCriteriaDisplay();

            angular.element($window).on('scroll', $scope.loadMoreOnWindowScroll);
            $scope.$on('$destroy', function () {
                angular.element($window).off('scroll', $scope.loadMoreOnWindowScroll);
            });
        }


        function setCriteriaDisplay() {
            $scope.criteria = {};
            $scope.criteriaReady = false;

            if ($stateParams.zip) {
                $scope.criteria.zip = $stateParams.zip;
            }

            if ($stateParams.name) {
                $scope.criteria.name = $stateParams.name;
            }

            if ($stateParams.state || $stateParams.county || $stateParams.city) {
                StatesService.statesPromise.then(function (states) {
                    var stateObj = states.find(function (x) { return x.stateId == $stateParams.state });

                    if (stateObj) {
                        $scope.criteria.state = stateObj.state;

                        if ($stateParams.county) {
                            var countyObj = stateObj.counties
                                .find(function (x) { return x.countyId == $stateParams.county });
                            $scope.criteria.county = countyObj.county;
                        }

                        if ($stateParams.city) {
                            var cityObj = stateObj.cities.find(function (x) { return x.cityId == $stateParams.city });
                            $scope.criteria.city = cityObj.city;
                        }
                    } else {
                        if ($stateParams.county) {
                            _(states)
                                .forEach(function (stateObj) {
                                    var countyObj = stateObj.counties
                                        .find(function (x) { return x.countyId == $stateParams.county });
                                    if (countyObj) {
                                        $scope.criteria.county = countyObj.county;
                                        return false;
                                    }
                                });
                        }

                        if ($stateParams.city) {
                            _(states)
                                .forEach(function (stateObj) {
                                    var cityObj = stateObj.cities.find(function (x) { return x.cityId == $stateParams.city });
                                    if (cityObj) {
                                        $scope.criteria.city = cityObj.city;
                                        return false;
                                    }
                                });
                        }
                    }

                    $scope.criteriaReady = true;
                });
            } else {
                $scope.criteriaReady = true;
            }
        }


        function setSearchResults() {
            var params = {
                name: $stateParams.name,
                stateId: $stateParams.state,
                countyId: $stateParams.county,
                cityId: $stateParams.city,
                zip: $stateParams.zip
            };

            $scope.instDataReady = false;
            InstitutionsService.query(params).then(function (result) {
                $scope.instData = result;
                $scope.totalInstCount = $scope.instData.length;
                $scope.instDataReady = true;
            });
        }


    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('InstitutionsController', InstitutionsController);

    InstitutionsController.$inject = ['$scope', '$rootScope', '$state', '$stateParams', 'StatesService', 'InstitutionsService', 'UserData', '$log'];

    function InstitutionsController($scope, $rootScope, $state, $stateParams, StatesService, InstitutionsService, UserData, $log) {
        // Define this here for all child states
        $rootScope.institution = { definition: null };

        $scope.statesLoaded = false;
        $scope.states = [];
        $scope.criteria = {
            name: null,
            state: null,
            county: null,
            city: null,
            zip: null
        };

        $scope.isBuyer = function () {
            return UserData.buyerInstitutions.isSaved($scope.institution.definition);
        };

        $scope.isTarget = function () {
            return UserData.targetInstitutions.isSaved($scope.institution.definition);
        };

        $scope.saveBuyerRSSD = function () {
            if ($scope.isTarget($scope.institution.definition)) {
                UserData.targetInstitutions.remove($scope.institution.definition);
            }

            UserData.buyerInstitutions.save($scope.institution.definition);
        };

        $scope.saveTargetRSSD = function () {
            if ($scope.isBuyer($scope.institution.definition)) {
                UserData.buyerInstitutions.remove($scope.institution.definition);
            }

            UserData.targetInstitutions.save($scope.institution.definition);
        };

        activate();

        function activate() {
            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionSearchController', InstitutionSearchController);

    InstitutionSearchController.$inject = ['$scope', '$state', '$stateParams', '$log', 'store'];

    function InstitutionSearchController($scope, $state, $stateParams, $log, store) {
        var storeKey = 'instSearchCri';
        $scope.instSearchSubmit = function () {
            var el = document.getElementById("city");
            var cityName = el.options[el.selectedIndex].label;

            var data = {
                name: $scope.criteria.name,
                state: $scope.criteria.state ? $scope.criteria.state.stateId : null,
                county: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                city: $scope.criteria.city ? $scope.criteria.city.cityId : null,
                zip: $scope.criteria.zip,
                cityname: cityName
            };
            store.set(storeKey, $scope.criteria);
            $state.go('^.list', data);
        };

        activate();

        function activate() {
            setCriteria();
        }

        function setCriteria() {
            if ($scope.keepSearchCriteria) {
                $scope.criteria = store.get(storeKey);
            } else
                $scope.criteria = {
                    name: null,
                    state: null,
                    county: null,
                    city: null,
                    zip: null
                };
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionDetailHistoryController', InstitutionDetailHistoryController);

    InstitutionDetailHistoryController.$inject = ['institution', 'institutionHistory', '$rootScope', '$scope','$stateParams'];

    function InstitutionDetailHistoryController(institution, institutionHistory, $rootScope, $scope, $stateParams) {
        $rootScope.institution.history = institutionHistory.history;
        $rootScope.institution.historyLoaded = true;
        $scope.rssdId = $stateParams.rssd;
        $scope.byYear = false;
        $scope.byBranch = false;

        angular.extend($scope, {
            historyReady: false,
            filter: "all",
            includeBranchTxns: true,
            checkNoResults: function () {
                return $rootScope.institution != null ? _.filter(_.flatMap($rootScope.institution.history, function (e) { return e.data }),
                        function (e) { return $scope.historyFilter(e) }).length == 0 : false;
            },
            branchTxnTypes: ["Openings", "Closings", "Sales", "Location Changes"],
            hasBranchTxnTypeFilter: function () {
                return _.indexOf(this.branchTxnTypes, this.filter) > -1;
            },
            years: [],
            hasYearFilter: function () {
                return _.indexOf(this.years, this.filter) > -1;
            },
            setYearFilter: function (year) {
                $scope.filter = year;
                var yearChunk = _.find($rootScope.institution.history, { year: year });
                if (yearChunk) {
                    $scope.byYear = true;
                    $scope.byBranch = false;
                    yearChunk.isOpen = true;
                }
            },
            showBranchTransactions: true,
            clearBranchTxnTypeFilter: function () {
                if (!this.showBranchTransactions && this.hasBranchTxnTypeFilter()) {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    this.filter = "all";
                }
            },
            historyFilter: function (hist) {
                if (!$scope.showBranchTransactions && (hist.isBranchOpening || hist.isBranchClosing || hist.isBranchSale || hist.isBranchRelocation)) {
                    return false;
                }
                if ($scope.filter == 'all') {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    return true;
                }
                if ($scope.filter == 'mergers') {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                     return hist.isMerger;
                }
                if ($scope.filter == 'acquisitions') {
                    $scope.byBranch = false;
                    $scope.byYear = false;
                    return hist.isAcquisition;
                }
                if ($scope.filter == 'Openings') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchOpening;
                }
                if ($scope.filter == 'Closings') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchClosing;
                }
                if ($scope.filter == 'Sales') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchSale;
                }
                if ($scope.filter == 'Location Changes') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchRelocation;
                }
                if ($scope.filter == 'failures') {         
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    return hist.isFailure;
                }
                if ($scope.filter == 'misc') {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    return hist.isMisc;
                }
                return true;
            },
            closeOpenAllYearGroups: function (open) {
                angular.forEach($rootScope.institution.history, function (obj, index) {
                    obj.isOpen = open === true ? true : open === false ? false : !obj.isOpen;
                });
            }
        });

        activate();

        function activate() {

            angular.forEach($rootScope.institution.history, function (val, key) {
                var year = val.year;
                if (_.indexOf($scope.years, year) === -1)
                    $scope.years.push(year);
            });

            $scope.years.sort().reverse();

            var historyByYear = [];
            for (var i = 0; i < $scope.years.length; i++) {
                var year = $scope.years[i];
                var chunk = _.filter($rootScope.institution.history, { year: year });

                historyByYear.push({ year: year, data: chunk, isOpen: true });
            }
            //console.log(historyByYear);
            $rootScope.institution.history = historyByYear;

            $scope.historyReady = true;

            


            
        }
        $scope.MoveUp = function () {
            window.scrollTo(0, 0);
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionDetailOpMarketController', InstitutionDetailOpMarketController);

    InstitutionDetailOpMarketController.$inject = ['institution', 'institutionMarkets', '$rootScope', '$scope', '$stateParams', 'UserData', '$log'];

    function InstitutionDetailOpMarketController(institution, institutionMarkets, $rootScope, $scope, $stateParams, UserData, $log) {
        $rootScope.institution.markets = institutionMarkets.markets;
        $rootScope.institution.marketsLoaded = true;
        $scope.instData = [];
        $scope.instDataReady = false;

        $scope.saveMarket = function (market) {
            UserData.markets.save(market);
        };
        $scope.isSavedMarket = function (id) {
            return UserData.markets.isSaved(id);
        };
        $scope.removeMarket = function (market) {
            UserData.markets.remove(market.marketId);
        };
        $scope.toggleMarket = function (market) {
            if (UserData.markets.isSaved(market.marketId))
                UserData.markets.remove(market.marketId);
            else
                UserData.markets.save(market);
        };

        $scope.gridDisplay = null;
        $scope.setGridDisplay = setGridDisplay;

        activate();

        function activate() {
            $scope.setGridDisplay('byMarket');
            $scope.isFiltered = $stateParams.city || $stateParams.state || $stateParams.county || $stateParams.zip;
        }

        function setGridDisplay(gridDisplayVal) {
            $scope.gridDisplay = gridDisplayVal;
            $scope.instData = formatDataForMarkets(institutionMarkets.markets);
            $scope.instDataReady = true;
        }

        function formatDataForMarkets(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                if (rec.marketId <= 0) continue;

                if ($scope.gridDisplay == "byMarket") {
                    var county = { county: rec.county, state: rec.state };
                    var market = _.find(newData, { marketId: rec.marketId });

                    if (typeof market == "undefined") {//already added market to data variable?
                        market = {
                            marketId: rec.marketId,
                            marketName: rec.marketName,
                            countyList: [county]

                        }; //create new
                        newData.push(market);
                    } else
                        market.countyList.push(county);
                }
                else if ($scope.gridDisplay == "byCounty") {
                    var market = { marketName: rec.marketName, marketId: rec.marketId };
                    var county = _.find(newData, { county: rec.county });

                    if (typeof county == "undefined") {//already added market to data variable?
                        county = {
                            county: rec.county,
                            state: rec.state,
                            marketList: [market],
                            marketName: market.marketName

                        }; //create new
                        newData.push(county);
                    } else
                        county.marketList.push(market);
                }
            }
            return newData;
        }
    }
})();

;
(function () {
    "use strict";

    angular
      .module("app")
      .controller("InstitutionDetailOrgsController", InstitutionDetailOrgsController);

    InstitutionDetailOrgsController.$inject = ["institution", "institutionOrgs", "$scope", "$rootScope", "$stateParams", "ProFormaService", "$log", "$state", 'store', 'StatesService', 'Dialogger'];

    function InstitutionDetailOrgsController(institution, institutionOrgs, $scope, $rootScope, $stateParams, ProFormaService, $log, $state, store, StatesService, Dialogger) {
        $rootScope.institution.branches = institutionOrgs.branches;
        $rootScope.institution.definition.branchDeposits = getTotalDeposits($rootScope.institution.branches);
        //$scope.branchDeposits = getTotalDeposits($rootScope.institution.branches);
        $rootScope.institution.branchesLoaded = true;
        $scope.criteriaReady = false;
        $scope.toggleBranchTarget = toggleBranchTarget;
        $scope.isSavedBranch = isSavedBranch;
        $scope.instPageSize = 30;
        $scope.name = $stateParams.name;
        $scope.state = $stateParams.state;
        $scope.city = $stateParams.city,
        $scope.county = $stateParams.county;
        $scope.zip = $stateParams.zip;
        activate();

        function activate() {
            setCriteriaDisplay();
            ProFormaService.clearBuyer();
            ProFormaService.clearTargets();

            $scope.instData = $rootScope.institution.definition.orgType === "Tophold"
                ? $rootScope.institution.definition.orgs
                : $rootScope.institution.branches;
            $scope.orgType = $rootScope.institution.definition.orgType;
            $scope.isFiltered = $stateParams.city || $stateParams.state || $stateParams.county || $stateParams.zip;
            $scope.inst = $rootScope.institution.definition;
        }

        function toggleBranchTarget(inst, branch) {
            ProFormaService.toggleBranch(inst, branch);
        }
        function getOrg() {
            var params = {
                name: $stateParams.name,
                stateId: $stateParams.state,
                countyId: $stateParams.county,
                cityId: $stateParams.city,
                zip: $stateParams.zip
            };

            var criteria = {
                rssdId: $scope.inst.rssdId,
                getDetail: true,
                getBranches: true,
                getOperatingMarkets: true,
                getHistory: true,
                zip: null,
                state: null,
                county: null,
                city: null
            };

            $scope.instDataReady = false;
            InstitutionsService.get(params).then(function (result) {
                $scope.instData = result;
                $scope.instDataReady = true;
            });
        }
        function isSavedBranch(branch) {
            return ProFormaService.isSavedBranch(branch);
        }
        $scope.clearAll = function () {
            var rssdId = $scope.inst.rssdId;
            $scope.criteria = {
                name: null,
                state: null,
                county: null,
                city: null,
                zip: null
            };
           
            $stateParams.state = null;
            $stateParams.city = null,
            $stateParams.county = null;
            $stateParams.zip = null;
            $stateParams.rssd = $scope.inst.rssdId;
           // $state.go('root.institutions.summary.orgs', { rssd: rssdId, zip: null, county: null, state: null, city: null });
            $state.go('root.institutions.summary.orgs', { rssd: rssdId, zip: null, county: null, state: null, city: null }, { reload: true });
        }
        function getTotalDeposits(branchesArray) {
            var total = 0;
            for (var i = 0; i < branchesArray.length; i++) {
                total += branchesArray[i].deposits;
            }
            return total;
        }

        function setCriteriaDisplay() {
            $scope.criteria = {};
            $scope.criteriaReady = false;

            if ($stateParams.zip) {
                $scope.criteria.zip = $stateParams.zip;
            }

            if ($stateParams.name) {
                $scope.criteria.name = $stateParams.name;
            }

            if ($stateParams.state || $stateParams.county || $stateParams.city) {
                StatesService.statesPromise.then(function (states) {
                    var stateObj = states.find(function (x) { return x.stateId == $stateParams.state });

                    if (stateObj) {
                        $scope.criteria.state = stateObj.state;

                        if ($stateParams.county) {
                            var countyObj = stateObj.counties
                                .find(function (x) { return x.countyId == $stateParams.county });
                            $scope.criteria.county = countyObj.county;
                        }

                        if ($stateParams.city) {
                            var cityObj = stateObj.cities.find(function (x) { return x.cityId == $stateParams.city });
                            $scope.criteria.city = cityObj.city;
                        }
                    } else {
                        if ($stateParams.county) {
                            _(states)
                                .forEach(function (stateObj) {
                                    var countyObj = stateObj.counties
                                        .find(function (x) { return x.countyId == $stateParams.county });
                                    if (countyObj) {
                                        $scope.criteria.county = countyObj.county;
                                        return false;
                                    }
                                });
                        }

                        if ($stateParams.city) {
                            _(states)
                                .forEach(function (stateObj) {
                                    var cityObj = stateObj.cities.find(function (x) { return x.cityId == $stateParams.city });
                                    if (cityObj) {
                                        $scope.criteria.city = cityObj.city;
                                        return false;
                                    }
                                });
                        }
                    }

                    $scope.criteriaReady = true;
                });
            } else {
                $scope.criteriaReady = true;
            }
        }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('InstitutionSummaryController', InstitutionSummaryController);

    InstitutionSummaryController.$inject = ['institution','$rootScope', '$log', '$scope', '$state','$stateParams'];

    function InstitutionSummaryController(institution, $rootScope, $log, $scope, $state, $stateParams) {
        $rootScope.institution.definition = institution.definition;
        $scope.branchDeposits = getTotalDeposits(institution.branches);
        $rootScope.institutionLoaded = true;
        $scope.state = $stateParams.state;
        $scope.city = $stateParams.city,
        $scope.county = $stateParams.county;
        $scope.zip = $stateParams.zip;

        $scope.tabs = [
            { heading: "*", route: "root.institutions.summary.orgs", active: false },
                      { heading: "Operating Markets", route: "root.institutions.summary.markets", active: false },
                      { heading: "History", route: "root.institutions.summary.history", active: false }
        ];
        $scope.go = goToRoute;
        $scope.active = isActiveRoute;
        activate();

        function activate() {
            $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
                if (toState.resolve) {
                    $scope.tabLoading = true;
                        }
                    });
            $scope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
                if (toState.resolve) {
                    $scope.tabLoading = false;
                }
                    $scope.tabs.forEach(function (tab) {
                    tab.active = $scope.active(tab.route);
                    });
            });

            $scope.tabs[0].heading = institution.definition.orgType === "Tophold"
                        ? "Subsidiary Institutions"
                        : "Branches";
    }

        function goToRoute(route) {
            $state.go(route, { rssd: $state.params.rssd });
                    }

        function isActiveRoute(route) {
            return $state.is(route);
        }
        function getTotalDeposits(branchesArray) {
            var total = 0;
            for (var i = 0; i < branchesArray.length; i++) {
                total += branchesArray[i].deposits;
            }
            return total;
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketBrowseController', MarketBrowseController);

    MarketBrowseController.$inject = ['$scope', '$state', 'StatesService'];

    function MarketBrowseController($scope, $state, StatesService) {

        $scope.hasState = false;

        activate();

        function activate() {
            //if (!$scope.$parent.states || $scope.$parent.states.length == 0) {
            //    //load states from service if necessary (e.g., full page reload)
            //    StatesService.query().$promise.then(function (result) {
            //        $scope.$parent.states = result;
            //        $scope.$parent.statesLoaded = true;
            //    });
            //}
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketBrowseCountiesController', MarketBrowseCountiesController);

    MarketBrowseCountiesController.$inject = ['$scope', '$state', '$stateParams', 'StatesService'];

    function MarketBrowseCountiesController($scope, $state, $stateParams, StatesService) {
        if (!$stateParams.state) {
            $state.go("^");
            return;
        }

        $scope.hasState = true;
        $scope.stateName = $stateParams.state;
        $scope.stateId = 0;
        $scope.counties = [];
        $scope.countiesReady = false;

        activate();

        function activate() {
            StatesService.statesPromise.then(function (result) {
                var states = result,
                    state = _.find(states, { state: $stateParams.state });

                $scope.stateId = state.stateId;
                $scope.counties = state.counties;
                $scope.countiesReady = true;
            });
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketListController', MarketListController);

    MarketListController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'MarketsService', 'StatesService', '$location', '$window'];

    function MarketListController($scope, $state, $stateParams, $timeout, $templateCache, MarketsService, StatesService, $location, $window) {
        $scope.byCountyData = [];
        $scope.byMarketData = [];
        $scope.dataReady = false;
        $scope.gridDisplay = "byMarket";
        $scope.showMarketPagination = false;
        $scope.showCountyPagination = false;
        $scope.byMarketPageSize = 30;
        $scope.scrollLoadDefaultCount = 30;
        $scope.scrollLoadBatchSize = 30;
        $scope.mktScrollLoadCount = $scope.scrollLoadDefaultCount;
        $scope.stateScrollLoadCount = $scope.scrollLoadDefaultCount;
        $scope.totalMktViewCount = 0;
        $scope.totalStateViewCount = 0;
        $scope.showMoreLinkVisible = false;

        $scope.setGridDisplay = function (type) {
            $scope.gridDisplay = type;

            $scope.showMarketPagination = (type == 'byMarket');
            $scope.showCountyPagination = (type == 'byCounty');
        };

        $scope.showByMarket = function () {
            return $scope.gridDisplay == "byMarket";
        };

        $scope.showByCounty = function () {
            return $scope.gridDisplay == "byCounty";
        };

        $scope.removeCriteria = function (criterionName) {
            delete $scope.criteria[criterionName];
            var search = $location.search();
            delete search[criterionName];
            $location.search(search);

            if (_.isEmpty($scope.criteria))
                $state.go("^");
            else
                setSearchResults();
        }

        $scope.mktResetLoadMoreCounter = function () { $scope.mktScrollLoadCount = $scope.scrollLoadDefaultCount; };
        $scope.stateResetLoadMoreCounter = function () { $scope.stateScrollLoadCount = $scope.scrollLoadDefaultCount; };

        $scope.loadMoreOnWindowScroll = function (ignoreWindowPosition) {
            $scope.$apply(function () {
                if ($(window).scrollTop() > $(document).height() - $(window).height() - 125)
                {
                    if ($scope.gridDisplay == "byMarket") {
                        if ($scope.mktScrollLoadCount < $scope.totalMktViewCount) {
                            $scope.mktScrollLoadCount = $scope.mktScrollLoadCount + $scope.scrollLoadBatchSize;
                            $scope.searchState = 'scrollLoading';
                        }
                    }
                    else 
                    {
                        if ($scope.stateScrollLoadCount < $scope.totalStateViewCount) {
                            $scope.stateScrollLoadCount = $scope.stateScrollLoadCount + $scope.scrollLoadBatchSize;
                            $scope.searchState = 'scrollLoading';
                        }
                    }                    
                }
            });
        }

        $scope.visibleTabHasMore = function () {
            if ($scope.gridDisplay == "byMarket") {
                return $scope.mktScrollLoadCount < $scope.totalMktViewCount;
            }
            else {
                return $scope.stateScrollLoadCount < $scope.totalStateViewCount;
            }
        }

        $scope.loadMoreOnLinkClick = function () {
            if ($scope.gridDisplay == "byMarket") {
                if ($scope.mktScrollLoadCount < $scope.totalMktViewCount)
                {
                    $scope.mktScrollLoadCount = $scope.mktScrollLoadCount + $scope.scrollLoadBatchSize;
                    $scope.searchState = 'scrollLoading';
                }
            }
            else
            {
                if ($scope.stateScrollLoadCount < $scope.totalStateViewCount) {
                    $scope.stateScrollLoadCount = $scope.mktScrollLoadCount + $scope.scrollLoadBatchSize;
                    $scope.searchState = 'scrollLoading';
                }
            }            
        }

        $scope.onLoadMoreComplete = function () {
            $scope.clearLoadingMoreMsg();
        }

        $scope.clearLoadingMoreMsg = function () {
            $timeout(function () { $scope.searchState = 'loaded'; }, 3000);
        }

        activate();

        function activate() {
            setSearchResults(true);
            setCriteriaDisplay();
           
            angular.element($window).on('scroll', $scope.loadMoreOnWindowScroll);
            $scope.$on('$destroy', function () {
                angular.element($window).off('scroll', $scope.loadMoreOnWindowScroll);
            });
        }

        function setCriteriaDisplay() {
            $scope.criteria = {};
            $scope.criteriaReady = false;

            if ($stateParams.zip) {
                $scope.criteria.zip = $stateParams.zip;
            }

            if ($stateParams.state || $stateParams.county || $stateParams.city) {
                StatesService.statesPromise.then(function (states) {
                    var stateObj = states.find(function (x) { return x.stateId == $stateParams.state });

                    if (stateObj) {
                        $scope.criteria.state = stateObj.state;

                        if ($stateParams.county) {
                            var countyObj = stateObj.counties
                                .find(function (x) { return x.countyId == $stateParams.county });
                            $scope.criteria.county = countyObj.county;
                        }

                        if ($stateParams.city) {
                            var cityObj = stateObj.cities.find(function (x) { return x.cityId == $stateParams.city });
                            $scope.criteria.city = cityObj.city;
                        }
                    } else {
                        if ($stateParams.county) {
                            _(states)
                                .forEach(function (stateObj) {
                                    var countyObj = stateObj.counties
                                        .find(function (x) { return x.countyId == $stateParams.county });
                                    if (countyObj) {
                                        $scope.criteria.county = countyObj.county;
                                        return false;
                                    }
                                });
                        }

                        if ($stateParams.city) {
                            _(states)
                                .forEach(function (stateObj) {
                                    var cityObj = stateObj.cities.find(function (x) { return x.cityId == $stateParams.city });
                                    if (cityObj) {
                                        $scope.criteria.city = cityObj.city;
                                        return false;
                                    }
                                });
                        }
                    }

                    $scope.criteriaReady = true;
                });
            } else {
                $scope.criteriaReady = true;
            }
        }

        function setSearchResults(firstTime) {
            var searchParams = {
                stateId: $stateParams.state,
                countyId: $stateParams.county,
                cityId: $stateParams.city,
                zip: $stateParams.zip
            };

            $scope.dataReady = false;
            MarketsService.query(searchParams).then(function (result) {
                //create two variations of the data
                $scope.byCountyData = result;
                $scope.byMarketData = formatDataForMarkets(result);

                // HACK!    The pagination was insisting on showing up on initial page display as if it was the 'byCounty' 
                //          table, though are 2 different st-pagination directives, one on each table. Don't know why it's 
                //          happening but thought delaying the display might help and it does. ARGHHH!
                //if (firstTime) $timeout(function () { $scope.showMarketPagination = true; }, 10);
                $scope.totalMktViewCount = $scope.byMarketData.length;
                $scope.totalStateViewCount = $scope.byCountyData.length;
                $scope.dataReady = true;

                if ($scope.byMarketData.length == 0) {
                    MarketsService.getDistrictContact(result[0].districtId).then(function (result) {
                        $scope.districtContactInfo = result;
                    })
                   
                }
            });
        }

        function formatDataForMarkets(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                if (rec.marketId <= 0) continue;

                var county = { countyName: rec.countyName, statePostalCode: rec.statePostalCode };
                var market = _.find(newData, { marketId: rec.marketId });

                if (!market) { //already added market to data variable?
                    market = {
                        marketId: rec.marketId,
                        marketName: rec.marketName,
                        counties: [county]
                    }; //create new
                    newData.push(market);
                } else
                    market.counties.push(county);

            }
            newData.sort(function (a, b) {
                return a.marketName < b.marketName
                    ? -1
                    : a.marketName > b.marketName
                        ? 1
                        : 0;
            });
            return newData;
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('MarketsController', MarketsController);

    MarketsController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'UserData'];

    function MarketsController($scope, $rootScope, $state, StatesService, UserData) {
        $scope.statesLoaded = false;
        $scope.states = [];
        $scope.criteria = {
            state: null,
            county: null,
            city: null,
            zip: null
        };
        $scope.isSavedMarket = isSavedMarket;
		$scope.toggleMarket = toggleSavedMarket;
		$scope.hasPartialCounty = false;

		$scope.isMultiMarketCounty = function (county) {
			if ($scope.market
				&& $scope.market.definition
				&& $scope.market.definition.multiMarketCountyNames
				&& _.find($scope.market.definition.multiMarketCountyNames, { 'name': county.name, 'stateCode' : county.stateCode })
			) {
				$scope.hasPartialCounty = true;
				return true;
			}
			return false;
		}

        activate();

        function activate() {
            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
        }

        function isSavedMarket() {
            return UserData.markets.isSaved(parseInt($state.params.market, 10));
		}

		

        function toggleSavedMarket() {
            var marketObj = { marketId: parseInt($state.params.market, 10), name: $rootScope.market.definition.name };
            if (isSavedMarket())
                UserData.markets.remove(marketObj);
            else
                UserData.markets.save(marketObj);
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketSearchController', MarketSearchController);

    MarketSearchController.$inject = ['$scope', '$state', 'store'];

    function MarketSearchController($scope, $state, store) {
        var storeKey = 'marketSearchCri';
        $scope.marketSearchSubmit = function () {
            var data = {
                state: $scope.criteria.state ? $scope.criteria.state.stateId : null,
                county: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                city: $scope.criteria.city ? $scope.criteria.city.cityId : null,
                zip: $scope.criteria.zip
            };
            store.set(storeKey, $scope.criteria);
            $state.go('^.list', data);
        };

        activate();

        function activate() {
            setCriteria();
        }

        function setCriteria() {
            if ($scope.keepSearchCriteria)
                $scope.criteria = store.get(storeKey);
            else
                $scope.criteria = {
                    state: null,
                    county: null,
                    city: null,
                    zip: null
                };
        }

    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketDetailController', MarketDetailController);

    MarketDetailController.$inject = ['marketDef', '$rootScope', '$scope', '$state'];

    function MarketDetailController(marketDef, $rootScope, $scope, $state) {
        $scope.tabs = [
            { heading: "Definition", route: "root.markets.detail.definition", active: false },
            { heading: "Structure & HHI", route: "root.markets.detail.hhi", active: false },
            { heading: "Map", route: "root.markets.detail.map", active: false },
            { heading: "History", route: "root.markets.detail.history", active: false }
        ];
        $scope.go = function (route) {
            $state.go(route);
        };
        $scope.active = function (route) {
            return $state.is(route);
        };
        $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (toState.resolve) {
                $scope.tabLoading = true;
            }
        });
        $scope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
            if (toState.resolve) {
                $scope.tabLoading = false;
            }
            $scope.tabs.forEach(function (tab) {
                tab.active = $scope.active(tab.route);
            });
        });

        $rootScope.market = $rootScope.market || {};
        $rootScope.market.definition = marketDef.definition;
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketDetailDefinitionController', MarketDetailDefinitionController);

    MarketDetailDefinitionController.$inject = ["marketDef", "$rootScope"];

    function MarketDetailDefinitionController(marketDef, $rootScope) {
        $rootScope.market = $rootScope.market || {};
        $rootScope.market.definition = marketDef.definition;
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('MarketDetailHhiController', MarketDetailHhiController);

    MarketDetailHhiController.$inject = ['marketDef', 'marketHhi', '$scope', '$rootScope', '$stateParams', 'UserData', 'ProFormaService', 'MarketsService', 'genericService', '$window', '$timeout'];

    function MarketDetailHhiController(marketDef, marketHhi, $scope, $rootScope, $stateParams, UserData, ProFormaService, MarketsService, genericService, $window, $timeout) {
        $rootScope.market = $rootScope.market || {};
        $rootScope.market.definition = marketDef.definition;
        $rootScope.market.hhi = marketHhi.hhi;


        angular.extend($scope, {
            hhiData: marketHhi.hhi.orgs,
            hhiDataReady: true,
            sodDate: '',
            clearTargets: clearTargets
        });

        $scope.scrollLoadDefaultCount = 10;
        $scope.scrollLoadBatchSize = 1;
        $scope.scrollLoadCount = $scope.scrollLoadDefaultCount;
        $scope.totalInstCount = $scope.hhiData.length;
        $scope.showMoreLinkVisible = false;

        $scope.resetLoadMoreCounter = function () { $scope.scrollLoadCount = $scope.scrollLoadDefaultCount; };

        $scope.loadMoreOnWindowScroll = function (ignoreWindowPosition) {
            $scope.$apply(function () {
                if (($scope.scrollLoadCount < $scope.totalInstCount) && ($(window).scrollTop() > $(document).height() - $(window).height() - 355)) {
                    $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                    $scope.searchState = 'scrollLoading';
                }
            });
        }

        $scope.loadMoreOnLinkClick = function () {
            if ($scope.scrollLoadCount < $scope.totalInstCount) {
                $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                $scope.searchState = 'scrollLoading';
            }
        }

        $scope.onLoadMoreComplete = function () {
            $scope.clearLoadingMoreMsg();
        }

        $scope.clearLoadingMoreMsg = function () {
            $timeout(function () { $scope.searchState = 'loaded'; }, 3000);
        }


        activate();

        function activate() {
            $scope.resetLoadMoreCounter();
            genericService.getSodDate().then(function (result) { $scope.sodDate = result; });
            ProFormaService.clearBuyer();
            ProFormaService.clearTargets();
            //ProFormaService.selections.load();

            angular.element($window).on('scroll', $scope.loadMoreOnWindowScroll);
            $scope.$on('$destroy', function () {
                angular.element($window).off('scroll', $scope.loadMoreOnWindowScroll);
            });
        }

        function clearTargets() {
            ProFormaService.clearTargets();
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketDetailHistoryController', MarketDetailHistoryController);

    MarketDetailHistoryController.$inject = ['marketDef', 'marketHistory', '$rootScope', '$scope', '$stateParams'];

    function MarketDetailHistoryController(marketDef, marketHistory, $rootScope, $scope, $stateParams) {
        $rootScope.market = $rootScope.market || {};
        $rootScope.market.definition = marketDef.definition;
        $rootScope.market.history = marketHistory.history;
        $scope.marketId = marketDef.definition.marketId;
        $rootScope.filter = "all";
        $scope.byYear = false;
        $scope.byBranch = false;

        angular.extend($scope, {
            historyReady: false,
            filter: "all",
            includeBranchTxns: true,
            
            checkNoResults: function () {
                return $scope.market != null ? _.filter(_.flatMap($scope.market.history, function (e) { return e.data }),
                        function (e) { return $scope.historyFilter(e) }).length == 0 : false;
            },
            branchTxnTypes: ["Openings", "Closings", "Sales", "Location Changes"],
            hasBranchTxnTypeFilter: function () {
                return _.indexOf(this.branchTxnTypes, this.filter) > -1
            },
            years: [],
            hasYearFilter: function () {
                return _.indexOf(this.years, this.filter) > -1;
            },
            setYearFilter: function (year) {
                $scope.filter = year;
                var yearChunk = _.find($scope.market.history, { year: year });
                if (yearChunk) {
                    $scope.byYear = true;
                    $scope.byBranch = false;
                    yearChunk.isOpen = true;
                }
            },
            showBranchTransactions: true,
            clearBranchTxnTypeFilter: function () {
                if (!this.showBranchTransactions && this.hasBranchTxnTypeFilter()) {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    this.filter = "all";
                }
            },
            historyFilter: function (hist) {
                $rootScope.filter = $scope.filter;
                if (!$scope.showBranchTransactions && (hist.isBranchOpening || hist.isBranchClosing || hist.isBranchSale || hist.isBranchRelocation)) {
                    return false;
                }
                if ($scope.filter == 'all') {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    return true;
                }
                if ($scope.filter == 'TopholdParent') {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    return hist.isTopholdAndInstitution;
                }
                if ($scope.filter == 'allbranchtrans') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranch;
                }
                //if ($scope.filter == 'mergers') {
                //    $scope.byYear = false;
                //    $scope.byBranch = false;
                //    return hist.isMerger;
                //}
                //if ($scope.filter == 'acquisitions') {
                //    $scope.byBranch = false;
                //    $scope.byYear = false;
                //    return hist.isAcquisition;
                //}
                if ($scope.filter == 'Openings') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchOpening;
                }
                if ($scope.filter == 'Closings') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchClosing;
                }
                if ($scope.filter == 'allbranchtrans') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranch;
                }
                if ($scope.filter == 'Sales') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchSale;
                }
                if ($scope.filter == 'Location Changes') {
                    $scope.byYear = false;
                    $scope.byBranch = true;
                    return hist.isBranchRelocation;
                }
                if ($scope.filter == 'failures') {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    return hist.isFailure;
                }
                if ($scope.filter == 'MarketDefintion') {
                    $scope.byYear = false;
                    $scope.byBranch = false;
                    return hist.isMarketDefinitionChange;
                }
                //if ($scope.filter == 'misc') {
                //    $scope.byYear = false;
                //    $scope.byBranch = false;
                //    return hist.isMisc;
                //}
                return true;
            },
            closeOpenAllYearGroups: function (open) {
                angular.forEach($scope.market.history, function (obj, index) {
                    obj.isOpen = open === true ? true : open === false ? false : !obj.isOpen;
                });
            }

        });

        activate();

        function activate() {


            angular.forEach($rootScope.market.history, function (val, key) {
                var year = val.year;
                if (_.indexOf($scope.years, year) == -1)
                    $scope.years.push(year);
            });

            $scope.years.sort().reverse();

            var historyByYear = [];
            for (var i = 0; i < $scope.years.length; i++) {
                var year = $scope.years[i];
                var chunk = _.filter($rootScope.market.history, { year: year });

                historyByYear.push({ year: year, data: chunk, isOpen: true });
            }
            //console.log(historyByYear);
            $rootScope.market.history = historyByYear;

            $scope.historyReady = true;
        }
        $scope.MoveUp = function () {
            window.scrollTo(0, 0);
        }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketDetailMapController', MarketDetailMapController);

    MarketDetailMapController.$inject = ['marketDef', 'marketMap', '$log', '$rootScope', '$scope', '$state', '$stateParams', 'MarketMapService', 'toastr', 'leafletData', 'leafletBoundsHelpers', 'ProFormaService'];

    function MarketDetailMapController(marketDef, marketMap, $log, $rootScope, $scope, $state, $stateParams, MarketMaps, toastr, leafletData, leafletBoundsHelpers, ProFormaService) {
        $rootScope.market = $rootScope.market || {};
        $rootScope.market.definition = marketDef.definition;
        $rootScope.market.map = marketMap.map;

        var year = (new Date()).getFullYear(),
            mapBoxAndOpenMapsAttribution = '&copy;' + year + ' <a href="https://www.mapbox.com/about/maps/">MapBox</a> &copy;' + year + ' <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>';

        angular.extend($scope, {
            mapReady: false,
            center: {},
            geoJson: {},
            layers: {
                overlays: {}
            },
            showBranches: false,
            toggleBranches: toggleBranches,
            showCounties: true, //affects map style
            showCities: true, //affects map style
            showRoads: true, //affects map style
            setMapStyle: setMapStyle,
            showMarket: true,
            toggleMarket: toggleMarket,
            showOtherMarkets: false,
            toggleOtherMarkets: toggleOtherMarkets,
            showStates: false,
            toggleStates: toggleStates,
            markers: {},
            hoveredMarket: null,
            targetBranch: targetBranch,
            marketUndefined: false,
            isMapShapeCurrent: true,
            mapStyles: {
                "CountiesRoadsCities": {
                    name: 'Counties, Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdk0r3001uganjch20akrs',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: true
                    }
                },
                "Counties": {
                    name: 'Counties Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhoaj50020ganjjg9cvcxi',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: false
                    }
                },
                "Roads": {
                    name: 'Roads Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhlhll001wg7ncl1gps309',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: false
                    }
                },
                "Cities": {
                    name: 'Cities Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdkdbp001gg8m4xzloqdl5',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: true
                    }
                },
                "CountiesRoads": {
                    name: 'Counties & Roads',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhsd0o001xg7nc6tkcbv4y',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: false
                    }
                },
                "RoadsCities": {
                    name: 'Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circddako001tganj2eqgiaph',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: true
                    }
                },
                "CountiesCities": {
                    name: 'Counties & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhhjbj001igfkvz8hqfkxe',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: true
                    }
                },
                "None": {
                    name: 'None',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'cirqcpxde002pg9nggrktu888',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: false
                    }
                }
            }
        });

        activate();

        function activate() {           
            setMapStyle();

            $scope.$on("leafletDirectiveGeoJson.leafy.mouseover",
                function (ev, leafletPayload) {

                    var layer = leafletPayload.leafletEvent.target,
                        feature = leafletPayload.leafletObject.feature;

                    layer.setStyle({
                        weight: 4,
                        color: "#000",
                        fillOpacity: 0.75
                    });
                    layer.bringToFront();

                    $scope.hoveredMarket = feature.properties;
                });

            $scope.$on("leafletDirectiveGeoJson.leafy.mouseout",
                function (ev, leafletPayload) {
                    $scope.hoveredMarket = null;
                });           

            $scope.$on("leafletDirectiveGeoJson.leafy.click",
                function (ev, leafletPayload) {
                    var feature = leafletPayload.leafletObject.feature;
                    $state.go("root.markets.detail.map", { market: feature.properties.marketId });
                });

            var bounds = null;
            if ($rootScope.market.map.geoJson) {
                bounds = leafletBoundsHelpers.createBoundsFromArray([
                    [$rootScope.market.map.geoJson.bbox[1], $rootScope.market.map.geoJson.bbox[0]],
                    [$rootScope.market.map.geoJson.bbox[3], $rootScope.market.map.geoJson.bbox[2]]
                ]);
                delete $rootScope.market.map.geoJson.bbox;
            }
            $scope.bounds = bounds;
            $scope.center = {};

            $scope.layers.overlays.market = {
                name: "theMarket",
                type: "geoJSONShape",
                data: $rootScope.market.map.geoJson,
                layerOptions: {
                    style: {
                        //fillColor: result.map.color || "#577492",
                        fillColor: "blue",
                        weight: 2,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.5
                    }
                },
                visible: true,
                layerParams: {
                    showOnSelector: false,
                }
            };

            $scope.marketUndefined = $rootScope.market.map.geoJson == null;
            $scope.isMapShapeCurrent = $rootScope.market.map.isMapShapeCurrent;
            $scope.mapReady = true;
        }

        var hasBranches = false, branchData = null;
        function toggleBranches() {            
            if (hasBranches) {
                $scope.showBranches = !$scope.showBranches;
                $scope.markers = $scope.showBranches ? branchData : {};
            } else {
                $scope.gettingBranches = true;
                MarketMaps.getBranches($stateParams.market) //caching at service layer
                    .then(function (result) {
                        var data = {};
                        for (var i = 0; i < result.length; i++) {
                            var br = result[i];
                            data["m" + br.id] = {
                                lat: br.latitude,
                                lng: br.longitude,
                                draggable: false,
                                message: "<a ui-sref='root.institutions.summary.orgs({rssd: " + br.instRssdId + "})'>" + br.instName + "</a>" +
                                    "<div><strong>" + br.name + "</strong></div>" +
                                    "<small>" + br.addr + "<br/>" + br.city + ", " + br.state + " " + br.zip + "</small>" /*+
                                    "<div class='text-right'>" +
                                    "<button class='btn btn-xs btn-primary' title='save this branch as a target' ng-click='targetBranch(" + br.id + ")'>Save <i class='fa fa-arrow-right'></i></button>" +
                                    "</div>"*/,
                                getMessageScope: function () { return $scope; }

                                //The following works, but is it likely a user will want to add Parent as target from map?
                                //"<div class='text-right'><span uib-dropdown>" +
                                //"<a href id='marker-dd-" + br.id + "' uib-dropdown-toggle>Save as Target <i class='fa fa-caret-down'></i></a>" +
                                //"<ul class='uib-dropdown-menu' aria-labelled-by='marker-dd-" + br.id + "'>" +
                                //"<li><a href ng-click='targetBranch(br)'>This Branch</a></li>" +
                                //"<li><a href ng-click='targetBranchParent(br)'>Branch's Parent</a></li>" +
                                //"</ul>" +
                                //"</span></div>"
                            };
                        }
                        $scope.markers = data;
                        branchData = data;
                        hasBranches = true;
                        $scope.gettingBranches = false;
                    });
            }
        }

        var hasStates = false, statesGeo = null;
        function toggleStates() {
            if ($scope.noStateData) return false;
            if (hasStates) {
                $scope.geoJson = $scope.showStates ? statesGeo : {};
            } else {
                $scope.gettingStates = true;
                MarketMaps.getStates($stateParams.market)
                    .then(function (result) {
                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                        }
                        else if (result.features.features.length == 0) {
                            $scope.noStateData = true;
                        }
                        else {
                            var colors = ["red", "yellow", "blue", "orange"],
                                colorIndex = 0;

                            var geoJson = {
                                data: result.features,
                                style: function (feature) {
                                    return {
                                        fillColor: colors[feature.id % colors.length],
                                        weight: 2,
                                        opacity: 0.5,
                                        color: "white",
                                        dashArray: "3",
                                        fillOpacity: 0.25
                                    }
                                },
                                resetStyleOnMouseout: true
                            };
                            $scope.geoJson = geoJson;
                            statesGeo = geoJson;
                            hasStates = true;
                        }

                        $scope.gettingStates = false;
                    });
            }
        }

        function toggleMarket() {            
            $scope.layers.overlays.market.visible = $scope.showMarket;
        }

        var hasOtherMarkets = false, otherMarketsGeo = null;
        function toggleOtherMarkets() {
            if (hasOtherMarkets) {
                $scope.showOtherMarkets = !$scope.showOtherMarkets;
                $scope.geoJson = $scope.showOtherMarkets ? otherMarketsGeo : {};
            } else {
                $scope.gettingOtherMarkets = true;
                MarketMaps.getSurroundingMarkets($stateParams.market)
                    .then(function (result) {

                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                            return;
                        }

                        var colors = ["red", "orange", "yellow", "green", "purple"];

                        var geoJson = {
                            data: result.features,
                            style: function (feature) {
                                return {
                                    fillColor: colors[feature.properties.index % colors.length],
                                    weight: 2,
                                    opacity: 0.5,
                                    color: "white",
                                    dashArray: "3",
                                    fillOpacity: 0.25
                                }
                            },
                            resetStyleOnMouseout: true
                        };
                        $scope.geoJson = geoJson;
                        otherMarketsGeo = geoJson;

                        hasOtherMarkets = true;
                        $scope.gettingOtherMarkets = false;
                    });
            }
        }

        function setMapStyle() {

            var tileSet = null;

            _.forEach($scope.mapStyles,
                function (t) {
                    if (t.data.counties === $scope.showCounties && t.data.cities === $scope.showCities && t.data.roads === $scope.showRoads) {
                        tileSet = t;
                        return false;
                    }
                });


            if (tileSet)
                $scope.tiles = tileSet;
        }
        

        function targetBranch(branchId) {
            $log.info("branchId", branchId);

            ProFormaService.saveBranchById(branchId);
        }
    }
})();
;
(function () {
    "use strict";

    angular
      .module("app")
      .factory("MarketMapService", MarketMapService);

    MarketMapService.$inject = ["$log", "$http"];

    function MarketMapService($log, $http) {
        var service = {
            getBranches: getBranches,
            getSurroundingMarkets: getSurroundingMarkets,
            getCounties: getCounties,
            getStates: getStates
        };

        return service;
        ////////////////

        function getBranches(marketId) {
            return $http.get("/api/markets/get-market-branches", { params: { marketId: marketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error retrieving map data", result);
                });
        }

        function getSurroundingMarkets(marketId) {
            return $http.post("/api/markets/get-surrounding-markets", {}, { params: { marketId: marketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error retrieving surrounding markets", result);
                });
		}

        function getStates(marketId) {
            return $http.post("/api/markets/get-market-states", {}, { params: { marketId: marketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error retrieving states", result);
                });
        }

        function getCounties(marketId, bbox) {
            return $http.post("/api/markets/get-market-counties", bbox, { params: { marketId: marketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error retrieving counties", result);
                });
        }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('MarketDetailMapController', MarketDetailMapController);

    MarketDetailMapController.$inject = ['marketDef', 'marketMap', '$log', '$rootScope', '$scope', '$state', '$stateParams', 'MarketMapService', 'toastr', 'leafletData', 'leafletBoundsHelpers', 'ProFormaService'];

    function MarketDetailMapController(marketDef, marketMap, $log, $rootScope, $scope, $state, $stateParams, MarketMaps, toastr, leafletData, leafletBoundsHelpers, ProFormaService) {
        $rootScope.market = $rootScope.market || {};
        $rootScope.market.definition = marketDef.definition;
        $rootScope.market.map = marketMap.map;

        var year = (new Date()).getFullYear(),
            mapBoxAndOpenMapsAttribution = '&copy;' + year + ' <a href="https://www.mapbox.com/about/maps/">MapBox</a> &copy;' + year + ' <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            cssAdded = false;

        angular.extend($scope, {
            mapReady: false,
            center: {},
            geoJson: {},
            layers: {
                overlays: {}
            },
            showBranches: false,
            toggleBranches: toggleBranches,
            toggleMapFullScreen: toggleMapFullScreen,
            addPrintClass: addPrintClass,
            printMap: printMap,
            showCounties: true, //affects map style
            showCities: true, //affects map style
            showRoads: true, //affects map style
            setMapStyle: setMapStyle,
            showMarket: true,
            toggleMarket: toggleMarket,
            showOtherMarkets: false,
            toggleOtherMarkets: toggleOtherMarkets,
            showStates: false,
            toggleStates: toggleStates,
            markers: {},
            hoveredMarket: null,
            targetBranch: targetBranch,
            marketUndefined: false,
            isMapShapeCurrent: true,
            mapStyles: {
                "CountiesRoadsCities": {
                    name: 'Counties, Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdk0r3001uganjch20akrs',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: true
                    }
                },
                "Counties": {
                    name: 'Counties Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhoaj50020ganjjg9cvcxi',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: false
                    }
                },
                "Roads": {
                    name: 'Roads Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhlhll001wg7ncl1gps309',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: false
                    }
                },
                "Cities": {
                    name: 'Cities Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdkdbp001gg8m4xzloqdl5',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: true
                    }
                },
                "CountiesRoads": {
                    name: 'Counties & Roads',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhsd0o001xg7nc6tkcbv4y',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: false
                    }
                },
                "RoadsCities": {
                    name: 'Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circddako001tganj2eqgiaph',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: true
                    }
                },
                "CountiesCities": {
                    name: 'Counties & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhhjbj001igfkvz8hqfkxe',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: true
                    }
                },
                "None": {
                    name: 'None',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'cirqcpxde002pg9nggrktu888',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: false
                    }
                }
            }
        });

        activate();

        function activate() {           
            if (!cssAdded) {
                // load in the print css
                cssAdded = true;
                var cssTag = document.createElement("link");
                cssTag.type = "text/css";
                cssTag.rel = "stylesheet";
                cssTag.href = "/content/css/mapPrint.css";
                document.getElementsByTagName("head")[0].appendChild(cssTag);
            }


            setMapStyle();

            $scope.$on("leafletDirectiveGeoJson.leafy.mouseover",
                function (ev, leafletPayload) {

                    var layer = leafletPayload.leafletEvent.target,
                        feature = leafletPayload.leafletObject.feature;

                    layer.setStyle({
                        weight: 4,
                        color: "#000",
                        fillOpacity: 0.75
                    });
                    layer.bringToFront();

                    $scope.hoveredMarket = feature.properties;
                });

            $scope.$on("leafletDirectiveGeoJson.leafy.mouseout",
                function (ev, leafletPayload) {
                    $scope.hoveredMarket = null;
                });

            $scope.$on('leafletDirectiveMap.leafy.load', function (event) {
                addPrintClass();
            });

            $scope.$on("leafletDirectiveGeoJson.leafy.click",
                function (ev, leafletPayload) {
                    var feature = leafletPayload.leafletObject.feature;
                    $state.go("root.markets.detail.map", { market: feature.properties.marketId });
                });

            var bounds = null;
            if ($rootScope.market.map.geoJson) {
                bounds = leafletBoundsHelpers.createBoundsFromArray([
                    [$rootScope.market.map.geoJson.bbox[1], $rootScope.market.map.geoJson.bbox[0]],
                    [$rootScope.market.map.geoJson.bbox[3], $rootScope.market.map.geoJson.bbox[2]]
                ]);
                delete $rootScope.market.map.geoJson.bbox;
            }
            $scope.bounds = bounds;
            $scope.center = {};

            $scope.layers.overlays.market = {
                name: "theMarket",
                type: "geoJSONShape",
                data: $rootScope.market.map.geoJson,
                layerOptions: {
                    style: {
                        //fillColor: result.map.color || "#577492",
                        fillColor: "blue",
                        weight: 2,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.5
                    }
                },
                visible: true,
                layerParams: {
                    showOnSelector: false,
                }
            };

            $scope.marketUndefined = $rootScope.market.map.geoJson == null;
            $scope.isMapShapeCurrent = $rootScope.market.map.isMapShapeCurrent;
            $scope.mapReady = true;
        }

        var hasBranches = false, branchData = null;
        function toggleBranches() {
            if (hasBranches) {
                $scope.showBranches = !$scope.showBranches;
                $scope.markers = $scope.showBranches ? branchData : {};
            } else {
                $scope.gettingBranches = true;
                MarketMaps.getBranches($stateParams.market) //caching at service layer
                    .then(function (result) {
                        var data = {};
                        for (var i = 0; i < result.length; i++) {
                            var br = result[i];
                            data["m" + br.id] = {
                                lat: br.latitude,
                                lng: br.longitude,
                                draggable: false,
                                message: "<a ui-sref='root.institutions.summary.orgs({rssd: " + br.instRssdId + "})'>" + br.instName + "</a>" +
                                    "<div><strong>" + br.name + "</strong></div>" +
                                    "<small>" + br.addr + "<br/>" + br.city + ", " + br.state + " " + br.zip + "</small>" /*+
                                    "<div class='text-right'>" +
                                    "<button class='btn btn-xs btn-primary' title='save this branch as a target' ng-click='targetBranch(" + br.id + ")'>Save <i class='fa fa-arrow-right'></i></button>" +
                                    "</div>"*/,
                                getMessageScope: function () { return $scope; }

                                //The following works, but is it likely a user will want to add Parent as target from map?
                                //"<div class='text-right'><span uib-dropdown>" +
                                //"<a href id='marker-dd-" + br.id + "' uib-dropdown-toggle>Save as Target <i class='fa fa-caret-down'></i></a>" +
                                //"<ul class='uib-dropdown-menu' aria-labelled-by='marker-dd-" + br.id + "'>" +
                                //"<li><a href ng-click='targetBranch(br)'>This Branch</a></li>" +
                                //"<li><a href ng-click='targetBranchParent(br)'>Branch's Parent</a></li>" +
                                //"</ul>" +
                                //"</span></div>"
                            };
                        }
                        $scope.markers = data;
                        branchData = data;
                        hasBranches = true;
                        $scope.gettingBranches = false;
                    });
            }
        }

        var hasStates = false, statesGeo = null;
        function toggleStates() {
            if ($scope.noStateData) return false;
            if (hasStates) {
                $scope.geoJson = $scope.showStates ? statesGeo : {};
            } else {
                $scope.gettingStates = true;
                MarketMaps.getStates($stateParams.market)
                    .then(function (result) {
                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                        }
                        else if (result.features.features.length == 0) {
                            $scope.noStateData = true;
                        }
                        else {
                            var colors = ["red", "yellow", "blue", "orange"],
                                colorIndex = 0;

                            var geoJson = {
                                data: result.features,
                                style: function (feature) {
                                    return {
                                        fillColor: colors[feature.id % colors.length],
                                        weight: 2,
                                        opacity: 0.5,
                                        color: "white",
                                        dashArray: "3",
                                        fillOpacity: 0.25
                                    }
                                },
                                resetStyleOnMouseout: true
                            };
                            $scope.geoJson = geoJson;
                            statesGeo = geoJson;
                            hasStates = true;
                        }

                        $scope.gettingStates = false;
                    });
            }
        }

        function printMap() {
            window.print();
        }

        function toggleMapFullScreen() {
            $scope.displayMapFullScreen = !$scope.displayMapFullScreen;
            if ($scope.displayMapFullScreen) {
                $("#leafy").addClass('fullScreenMap');
            }
            else {
                $("#leafy").removeClass('fullScreenMap');
            }

            leafletData.getMap()
                .then(function (map) {
                    map.invalidateSize();
                });
        }


        function addPrintClass() {
            $("#leafy, #leafy *").addClass("printMap");
            $("#leafy *").addClass("printMapChild");
            $("#leafy").parent().addClass("printMapContainer");
            $("#mapPartsSelectBox ul, #mapPartsSelectBox ul *").addClass("printMap");
            $('body').wrapInner('<div id="printBodyWrap" />');
        }

        function toggleMarket() {            
            $scope.layers.overlays.market.visible = $scope.showMarket;
        }

        var hasOtherMarkets = false, otherMarketsGeo = null;
        function toggleOtherMarkets() {
            if (hasOtherMarkets) {
                $scope.showOtherMarkets = !$scope.showOtherMarkets;
                $scope.geoJson = $scope.showOtherMarkets ? otherMarketsGeo : {};
            } else {
                $scope.gettingOtherMarkets = true;
                MarketMaps.getSurroundingMarkets($stateParams.market)
                    .then(function (result) {

                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                            return;
                        }

                        var colors = ["red", "orange", "yellow", "green", "purple"];

                        var geoJson = {
                            data: result.features,
                            style: function (feature) {
                                return {
                                    fillColor: colors[feature.properties.index % colors.length],
                                    weight: 2,
                                    opacity: 0.5,
                                    color: "white",
                                    dashArray: "3",
                                    fillOpacity: 0.25
                                }
                            },
                            resetStyleOnMouseout: true
                        };
                        $scope.geoJson = geoJson;
                        otherMarketsGeo = geoJson;

                        hasOtherMarkets = true;
                        $scope.gettingOtherMarkets = false;
                    });
            }
        }

        function setMapStyle() {

            var tileSet = null;

            _.forEach($scope.mapStyles,
                function (t) {
                    if (t.data.counties === $scope.showCounties && t.data.cities === $scope.showCities && t.data.roads === $scope.showRoads) {
                        tileSet = t;
                        return false;
                    }
                });


            if (tileSet)
                $scope.tiles = tileSet;
        }

        function targetBranch(branchId) {
            $log.info("branchId", branchId);

            ProFormaService.saveBranchById(branchId);
        }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('NewsModalController', NewsModalController);

    NewsModalController.$inject = ['$scope', '$uibModalInstance', 'item', 'NewsService'];

    function NewsModalController($scope, $uibModalInstance, item, News) {
        $scope.item = item;
        $scope.close = closeModal;
        $scope.dismissNews = dismissNewsItem;

        activate();

        function activate() { }

        function closeModal() {
            $uibModalInstance.dismiss('close');
        }

        function dismissNewsItem() {
            News.dismissByNewsId(item.newsId);
            item.dismissed = true;
            $uibModalInstance.dismiss('close');
        }
    }
})();
;

(function () {
    'use strict';

    angular
        .module('app')
        .controller('SideNavController', SideNavController);

    SideNavController.$inject = ['$scope', '$rootScope', 'AuthService', 'UserData', 'toastr', 'UtilityService', '$uibModal', '$log', 'AdvMarketsService', 'AdvInstitutionsService', '$http', '$state', 'DataSetService', 'MENU_ROLES', 'MenuService', 'Dialogger'];

    function SideNavController($scope, $rootScope, Auth, UserData, toastr, Util, $uibModal, $log, AdvMarketsService, AdvInstitutionsService, $http, $state, DataSets, MENU_ROLES, MenuService, Dialogger) {
        angular.extend($scope, {
            firstName: Auth.details.first,
            user: Auth.details,
            getInstitutions: UserData.institutions.get,
            getInstitutionCount: getInstitutionCount,
            removeInstitution: UserData.institutions.remove,
            addInstitution: handleAddInstitution,
            getMarkets: UserData.markets.get,
            removeMarket: function (mkt) { UserData.markets.remove(mkt.marketId) },
            addMarket: handleAddMarket,
            toTitleCase: Util.toTitleCase,
            UpdateMenu: UpdateMenu,
            handleExternalLink: handleExternalLink
        });

        activate();

        function activate() {
            // ***** MOVED TO NavController.js ****
            // ***** Needed to move because dataset selection has been moved to the main header navigation ******
            //// This call needs to be left here even though the list is used in the user preferences.
            //// This call could be moved but in Talking with Charles G. we decided to leave it.
            //DataSets.query().$promise.then(function (result) {
            //    $rootScope.dataSets = result;
            //    $rootScope.dataSet = _.find($scope.dataSets, { isUserChoice: true });                
            //});

            MenuService.SetSideNavCallBk($scope.UpdateMenu);

            if ($rootScope.menuData == undefined) {

                MenuService.GetMenuLayouts().then(function () {
                    MenuService.SetSelectedMenuLayout(Auth.details.menuLayoutId);
                    MenuService.BuildMenu($scope.user.roles);
                    $scope.menuItems = MenuService.GetMenu();
                });
            }
            else {
                $scope.menuItems = MenuService.GetMenu();
            }

            MenuService.GetMSDUrl().then(function (result) {
                $scope.showLinks = result.href.length > 0 && result.linkTitle.length > 0;
                $scope.msdLinkUrl = result.href;
                $scope.msdLinkTitle = result.linkTitle;
            });

            $scope.Reports = [];
            $http.get('/_jsondata/ReportLayoutStructureOnReportPage.json')
                .then(function (Result) {
                    $scope.Reports = Result.data;
                    $log.info("Data", Result.data);
                }, function (data, status, error, config) {
                    $scope.contents = [{ heading: "Error", description: "Could not load json   data" }];
                });
        }

        $scope.openEditMarketForm = function (market, mode) {
            AdvMarketsService.addOrEditMarket(market, mode);
        }


        $scope.openAddTopholdForm = function () {
            AdvInstitutionsService.addOrEditTophold();
        }

        $scope.openAddInstitutionForm = function () {
            $rootScope.isInWizard = true;
            AdvInstitutionsService.addOrEditInstitution();
        }


        $scope.callStructureWizard = function () {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: false,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/structure/views/_structureWizard.html',
                controller: 'AdvStructureWizardController'
            })
                .result.then(function () {
                    //dismissed
                });

        };

        $scope.showFlyout = function (item) {
            $("#" + item).show();
        };


        $scope.hideFlyout = function (item) {
            $("#" + item).hide();
        };




        function getInstitutionCount() {
            var insts = UserData.institutions.get();

            var count = 0;

            _.each(insts, function (e) {
                count += e.orgs.length;
                count++;
            });

            return count;
        }



        function findLocalInstitution(rssdId) {

            var result = null;
            var inst = _.find($scope.insts, { rssdId: rssdId });

            if (inst) {
                result = inst;
            } else {
                _.each($scope.insts,
                    function (e) {
                        var org = _.find(e.orgs, { rssdId: rssdId });

                        if (org)
                            result = org;
                    });
            }

            return result;
        }


        function handleExternalLink(externalUrl) {

            var confirmDialog = Dialogger.confirm("<strong>NOTICE:</strong> <br /><p>This link will take you outside of CASSIDI; and will open in a new window / tab</p> <p><strong>Do you want to continue?</strong></p>");

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    window.open(externalUrl, '_linkWin');
                }
            });
        }



        function handleAddInstitution() {
            $uibModal.open({
                size: 'lg',
                backdrop: 'static',
                keyboard: false,
                templateUrl: 'Appjs/advanced/sidenav/tpls/addInstitutionModal.html',
                controller: ["$uibModalInstance", "$scope", "UserData", "AdvInstitutionsService", "$timeout", "$state", function ($uibModalInstance, $scope, UserData, AdvInstitutionsService, $timeout, $state) {
                    $scope.insts = _.cloneDeep(UserData.institutions.get());
                    $scope.invalids = [];
                    $scope.removeds = [];
                    $scope.removedbranches = [];
                    $scope.newRssdId = null;

                    $scope.goToInstitution = function (rssdId, isTopHold) {
                        $uibModalInstance.dismiss();
                        $state.go('root.adv.institutions.summary.details', { rssd: rssdId, isTophold: isTopHold });
                    }

                    $scope.goToBranch = function (branchId) {
                        $uibModalInstance.dismiss();
                        $state.go('root.adv.institutions.branch.details', { branchId: branchId });
                    }

                    $scope.remove = function (inst) {

                        var removalInst = _.find($scope.insts, inst);

                        if (removalInst) {

                            _.each(removalInst.orgs,
                                function (e) {
                                    $scope.removeds.push(e);

                                });

                            _.pull($scope.insts, inst);
                            $scope.removeds.push(inst);

                        } else {
                            _.each($scope.insts, function (e) {
                                var removalOrg = _.find(e.orgs, inst);

                                if (removalOrg) {
                                    _.pull(e.orgs, inst);
                                    $scope.removeds.push(inst);
                                }
                            });
                        }

                    };

                    $scope.removeBranch = function (parent, branch) {

                        var removalInst = _.find($scope.insts, parent);

                        if (removalInst)
                            _.pull(removalInst.branches, branch);
                        else {
                            _.each($scope.insts, function (e) {
                                var removalOrg = _.find(e.orgs, parent);

                                if (removalOrg) {
                                    _.pull(removalOrg.branches, branch);
                                }
                            });
                        }

                        $scope.removedbranches.push(branch);
                    };

                    $scope.reAdd = function (inst) {

                        if (!findLocalInstitution(inst.rssdId)) {

                            if (inst.parentId) {
                                var foundParent = _.find($scope.removeds, { rssdId: inst.parentId });

                                if (foundParent) {
                                    inst = foundParent;
                                }
                            }

                            _.pull($scope.removeds, inst);

                            var foundInst = _.find($scope.insts, { rssdId: inst.parentId });

                            if (foundInst) {
                                foundInst.orgs.push(inst);
                            } else {
                                $scope.insts.push(inst);

                                if (inst.orgs.length > 0) {
                                    _.each(inst.orgs,
                                        function (e) {
                                            _.pull($scope.removeds, e);
                                        });
                                }
                            }
                        }
                    }

                    $scope.addRssdId = function () {

                        if (!findLocalInstitution($scope.newRssdId)) {

                            var newInst = {
                                rssdId: $scope.newRssdId,
                                name: "(unknown)",
                                validating: true,
                                invalid: false
                            }

                            $scope.invalidRssdId = null;
                            $scope.validatingRssdID = $scope.newRssdId;
                            $scope.newRssdId = null;

                            AdvInstitutionsService
                                .getNonHHIInstitutionsSearchData({ rssd: newInst.rssdId })
                                .then(function (result) {
                                    if (angular.isArray(result) && result.length == 1) {

                                        $scope.validatingRssdID = null;

                                        var foundInst = _.find($scope.insts, { rssdId: result[0].rssdId });

                                        if (foundInst) {

                                            if (result[0].orgs.length > 0) {

                                                var foundOrg = _
                                                    .find(foundInst.orgs, { rssdId: result[0].orgs[0].rssdId });

                                                if (!foundOrg) {
                                                    foundInst.orgs.push(result[0].orgs[0]);
                                                }

                                            }

                                        } else {
                                            $scope.insts.push(result[0]);
                                        }


                                    } else {
                                        $scope.invalidRssdId = $scope.validatingRssdID;
                                        $scope.validatingRssdID = null;
                                        $scope.invalids.push(newInst);


                                    }
                                });
                        } else {
                            $scope.newRssdId = null;
                        }

                    };

                    $scope.saveChanges = function () {
                        $uibModalInstance.close($scope.insts);
                    };
                }]
            }).result.then(function (result) {
                UserData.institutions.reset();
                _(result).forEach(UserData.institutions.save);

                if (result.length == 0)
                    toastr.warning("Your list of saved RSSDs is now empty.");
                else
                    toastr.success("Your list of saved RSSDs now contains " + _.join(_.map(result, "rssdId"), ", ") + ".");
            });
        }

        function handleAddMarket() {
            $uibModal.open({
                backdrop: 'static',
                keyboard: false,
                templateUrl: 'Appjs/advanced/sidenav/tpls/addMarketModal.html',
                controller: ["$uibModalInstance", "$scope", "UserData", "MarketsService", "$timeout", "uibDateParser", function ($uibModalInstance, $scope, UserData, MarketsService, $timeout, uibDateParser) {
                    $scope.markets = _.clone(UserData.markets.get());
                    $scope.invalids = [];
                    $scope.removeds = [];
                    $scope.newMarketNumber = null;

                    $scope.remove = function (mkt) {
                        _.pull($scope.markets, mkt);
                        $scope.removeds.push(mkt);
                    };

                    $scope.reAdd = function (mkt) {
                        _.pull($scope.removeds, mkt);
                        $scope.markets.push(mkt);
                    }

                    $scope.addMarket = function () {

                        if (!_.find($scope.markets, { marketId: $scope.newMarketNumber })) {


                            var newMkt = {
                                marketId: $scope.newMarketNumber,
                                marketName: "(unknown)",
                                validating: true,
                                invalid: false
                            }

                            $scope.markets.push(newMkt);
                            $scope.newMarketNumber = null;

                            var handleValidationFailure = function () {
                                var inst = $scope.markets[_.indexOf($scope.markets, newMkt)];
                                inst.validating = false;
                                inst.invalid = true;

                                $timeout(function () {
                                    _.pull($scope.markets, newMkt);
                                    $scope.invalids.push(newMkt);
                                },
                                    2500);
                            };

                            MarketsService
                                .get({ marketId: newMkt.marketId })
                                .then(function (result) {
                                    if (result && result.definition) {

                                        $scope.markets[_.indexOf($scope.markets, newMkt)] = UserData.markets
                                            .simplify(result.definition);
                                    } else {
                                        handleValidationFailure();
                                    }
                                },
                                    handleValidationFailure);
                        } else {
                            $scope.newMarketNumber = null;
                        }
                    };

                    $scope.printDiv = function (divName) {
                        var printContents = document.getElementById(divName).innerHTML;
                        var popupWin = window.open('', '_blank', 'width=800,height=800');
                        popupWin.document.open();
                        popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
                        popupWin.document.close();
                    }

                    $scope.saveChanges = function () {
                        $uibModalInstance.close($scope.markets);
                    };
                }]
            }).result.then(function (result) {
                UserData.markets.reset();
                _(result).forEach(UserData.markets.save);

                if (result.length == 0)
                    toastr.warning("Your list of saved markets is now empty.");
                else
                    toastr.success("Your list of saved markets now contains " + _.join(_.map(result, "marketId"), ", ") + ".");
            });
        }

        function UpdateMenu() {
            $scope.menuItems = MenuService.GetMenu();
        }

        //function BuildMenu()
        //{
        //    // DepInst
        //    // BnkMkt
        //    // HHIAnal
        //    // History
        //    // PendTrans
        //    // Reports
        //    // StrutChng
        //    // Admin
        //    if ($rootScope.menuData.selectedMenuLayout.menuLayoutId == MENU_ROLES.Default) {
        //        $scope.menuItems = ['DepInst', 'BnkMkt', 'HHIAnal', 'History', 'PendTrans', 'Reports', 'Admin', 'StrutChng'];
        //    }
        //    else {
        //        $scope.menuItems = ['DepInst', 'StrutChng', 'History', 'PendTrans', 'Reports', 'Admin', 'BnkMkt', 'HHIAnal'];
        //    }

        //}
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdminController', AdminController);

    AdminController.$inject = ['$rootScope', '$scope', '$state'];

    function AdminController($rootScope, $scope, $state) {
        angular.extend($scope, {
            isIndex: isOnIndexPage($state.current),
            //subTitle: getSubTitle($state.current),
        });

        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.isIndex = isOnIndexPage(toState);

            });
        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.admin";
        }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdminReportGeneratorController', AdminReportGeneratorController);

    AdminReportGeneratorController.$inject = ['$rootScope', '$scope', '$state', 'uiUploader', '$log', '$http', 'AdminService', '$timeout'];

    function AdminReportGeneratorController($rootScope, $scope, $state, uiUploader, $log, $http, AdminService, $timeout) {
        $scope.item = {};
        $scope.type = null;
        $scope.itemReady = false;
        $scope.results = [];
        $scope.todaysDate = new Date();
        $scope.selectedBranchRSSDs = [];
        $scope.setBranch = function(branchRSSDId)
        {            
            var selectedBranch = [];
            for (var i = 0; i < $scope.results.length; i++)
            {
                var selectedBranch = _.find($scope.results[i].branches, { branchRSSDId: branchRSSDId });
                if (selectedBranch != null) {
                    break;
                }
            }
           
            // is this branch already in the selectedBranchRSSDs array?
            // if it is, the user must be clicking to uncheck the item. We need to remove the branch
            var alreadySet = false;
            var numAlreadySelected = $scope.selectedBranchRSSDs ? $scope.selectedBranchRSSDs.length : 0;
            for (var i = 0; i < numAlreadySelected; i++)
            {
                if ($scope.selectedBranchRSSDs[i].branchRSSDId == selectedBranch.branchRSSDId)
                {
                    alreadySet = true;
                    $scope.selectedBranchRSSDs.splice(i, 1); // remove the branch from the array
                    break;
                }
            }

            if (!alreadySet) {
                $scope.selectedBranchRSSDs.push(selectedBranch);
            }
        }


        $scope.newUpload = function () {
            $scope.item = {};
            $scope.type = null;
            $scope.itemReady = false;
            $scope.results = [];
            $scope.todaysDate = new Date();
            $scope.selectedBranchRSSDs = [];
            window.scrollTo(0, 0);
        };

        $scope.selectAll = function () {
            // get the checkboxes and set then as selected
            var ckboxes = document.getElementsByClassName("brSelectCheckbox");
            for(var i=0; i<ckboxes.length; i++)
            {
                if (!ckboxes[i].checked)
                {
                    ckboxes[i].checked = true;
                }
            }
            
            // set the appropriate values in the scope's data variables
            $scope.selectedBranchRSSDs = [];  // clear any data from previous individually checked boxes
            var instData = $scope.results;
            for(var i=0; i<instData.length; i++)
            {
                var numBranches = instData[i].branches.length;
                for(var j=0; j<numBranches; j++)
                {
                   $scope.setBranch(instData[i].branches[j].branchRSSDId);
                }
            }
        }

        $scope.submitForm = function() {
            var data = { type: $scope.type, branches: $scope.selectedBranchRSSDs };// Posting data to php file
            $http({
                method  : 'POST',
                url     : 'Report/BranchOpenClose',
                data: data, //forms user object
                responseType: 'arraybuffer'
                //headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
            })
                .then(function (response) {
                //.success(function(data) {
                  if (response.data.errors) {
                      // Showing errors.
                      $scope.errorName = response.data.errors.name;
                      $scope.errorUserName = response.data.errors.username;
                      $scope.errorEmail = response.data.errors.email;
                  } else {
                      var blob = new Blob([response.data]);

                      if (window.navigator.msSaveOrOpenBlob) {

                          window.navigator.msSaveOrOpenBlob(blob, "Branch_" + $scope.type + "_" + year(date) + "-" + month(date) + "-" + +day(date) + ".pdf");
                     
                      } else {
                          
                          var date = new Date();
                          var year = date.getFullYear();
                          var month = date.getMonth();

                          var day = date.getDate();
                          var arr = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

                          var formatmonth = arr[month];
                          var link = document.createElement('a');
                          window.document.body.appendChild(link);
                          link.setAttribute("type", "hidden"); // make it hidden if needed
                          link.href = window.URL.createObjectURL(blob);
                          link.download = "Branch_" + $scope.type + "_" + year + "-" + formatmonth + "-" + day + ".pdf";

                          link.click();
                         
                      }
    
                      $scope.message = data.message;
                  }
              });
        };
        angular.extend($scope, {
            isIndex: isOnIndexPage($state.current),
            //subTitle: getSubTitle($state.current),
        });
        // Advanced--Uploading
        uiUploader.removeAll(); //must reset uploader between item edits
        $scope.handleAttachmentRemoval = function (key) {
            _.remove($scope.item.attachments, { key: key });
        };
        $scope.handleAttachmentUpload = function (type) {
            $scope.type = type;
            uiUploader.startUpload({
                url: '/Report/Upload/' + type,
                concurrency: 2,
                onProgress: function (file) {
                    $log.info(file.name, file);
                    $scope.$apply();
                },
                onCompleted: function (file, response) {
                    uiUploader.removeFile(file);
                   
                    if (typeof (response) == "string")
                        response = JSON.parse(response);

                    if (response.isOk) {
                        $scope.results = response.data;
                        $scope.totalCount = 0;
                        for (var i=0; i<$scope.results.length; i++)
                        {
                            $scope.totalCount += $scope.results[i].branches.length;
                        }
                    } else {
                        $log.error("error uploading ", file);
                        alert("Sorry. We had trouble uploading your file.");
                    }

                    $scope.$apply();
                }
            });
        };
        $scope.handleUploadChange = function (e) {
            var files = e.target.files;
            uiUploader.addFiles(files);
            $scope.item.uploads = uiUploader.getFiles();
            $scope.$apply();
        };
      
        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.isIndex = isOnIndexPage(toState);

            });
        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.admin";
        }
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('AdminService', AdminService);

    AdminService.$inject = ['$http', '$log', '$uibModal'];

    function AdminService($http, $log, $uibModal) {
        var service = {
			getUserListData: getUserListData,
			getInactiveNetworkUsers: getInactiveNetworkUsers,
            deleteUser: deleteUser,
            postresetPassword: postresetPassword,
            postunlockUser: postunlockUser,
            postEnableUser: postEnableUser,
            postDisableUser: postDisableUser,
            posteditUser: posteditUser,
            getUserById: getUserById,
            getRoles: getRoles,
            getAccountStatuses: getAccountStatuses,
            addOrEditUser: addOrEditUser,
            postaddUser: postaddUser,
            postUser: postUser,
            searchForUser: searchAdForUsers,
            getUsername: getUsername,
            updateMenuLayout: updateMenuLayout,
            getLQUpdateStatusSummary: getLQUpdateStatusSummary,
            getOutdatedLQReport: getOutdatedLQReport,
			updateLQValsFromNIC: updateLQValsFromNIC,
            getAssignableRoles: getAssignableRoles,
			getCaseWorkerEmails: getCaseWorkerEmails,
            getInstTypeValidationReport: getInstTypeValidationReport,
            getUniZeroBranches: getUniZeroBranches,
            updateBranchUninums: updateBranchUninums,
            postWarnExpiringUser: postWarnExpiringUser
        };

        return service;
        ////////////////
        

        function getUniZeroBranches() {
            return $http.get('/api/admin/GetUniZeroBranches')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning uninumber=0 branches", result);
                });
        }

        function updateBranchUninums(brIds, uninums) {
            var data = {
                BrIdCsv: brIds.join(','),
                UniNumCsv: uninums.join(',')
            };

            return $http.post('/api/admin/uniZeroUpdate', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error updating uninumbers", result);
                });
        }


        function getUserListData() {
            return $http.get('/api/adminusers/get-users')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
		}

		function getInactiveNetworkUsers() {
			return $http.get('/api/adminusers/getOldInternalUsers')
				.then(function Success(result) {
					return result.data;
				}, function Failure(result) {
					$log.error("Error getting old/invalid internal users", result);
				});
		}
        function getCaseWorkerEmails() {
            return $http.get('/api/adminusers/getCaseWorkerEmails')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                        $log.error("Error getting CaseWorker Emails", result);
                });
        }
        function getRoles() {
            return $http.get('/api/adminusers/get-roles')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
		}

		function getAssignableRoles() {
			return $http.get('/api/adminusers/get-assignable-roles')
				.then(function Success(result) {
					return result.data;
				}, function Failure(result) {
					$log.error("Error getting roles", result);
				});
		}		

        function getAccountStatuses() {
            return $http.get('/api/adminusers/get-account-statuses')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function getUserById(id) {
            return $http.get('/api/adminusers/get-user-by-id', { params: { userId: id } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function deleteUser(id) {
            return $http.post('/api/adminusers/delete-user', null, { params: { userId: id } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function postunlockUser(id) {
            return $http.post('/api/adminusers/unlock-user', null, { params: { userId: id } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function postEnableUser(id) {
            return $http.post('/api/adminusers/enable-user', null, { params: { userId: id } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function postDisableUser(id) {
            return $http.post('/api/adminusers/disable-user', null, { params: { userId: id } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function postresetPassword(id) {
            return $http.post('/api/adminusers/reset-user', null, { params: { userId: id } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function searchAdForUsers(searchTerm) {
            return $http
                .post("/api/adminusers/search-ad-for-user", { term: searchTerm })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function getUsername(first, last) {
            return $http
                .get("/api/adminusers/get-username", { params: { first: first, last: last } })
                .then(function Success(result) {
                    return result.data;
                },
                    function Failure(result) {
                        $log.error("Error returning username", result);
                    });
        }

        function postUser(userId, result) {
            return userId ? posteditUser(result) : postaddUser(result);
        }

        function addOrEditUser(userId) {

            return $uibModal
                .open({
                    animation: true,
                    modal: true,
                    size: 'lg',
                    templateUrl: 'AppJs/advanced/admin/views/editUsers.html',
                    controller: [
                        "$scope", "$state", "Dialogger", "userId", "$uibModalInstance", "$log",
                        editUsersController
                    ],
                    resolve: {
                        userId: function () {
                            return userId || null;
                        }
                    }
                })
                .result.then(function (result) {
                    return postUser(userId, result)
                        .then(function (data) {
                            if (!data.errorFlag) {
                                //Update row in user List
                                return data.user;
                            } else {
                                var errorMsgs = [];
                                if (data.messageTextItems.length > 0) {
                                    for (var i = 0; i < data.messageTextItems.length; i++) {
                                        errorMsgs.push(data.messageTextItems[i]);
                                    }
                                }
                                return { hasError: true, errorMsg: errorMsgs.join(" ") };
                            }
                        },
                        function (err) {
                            alert("Sorry. There was an error.");
                        });

                },
                function () {
                    //dismissed
                });
        }

        function posteditUser(data) {
            var data = { userId: data.userId, user: data.user };

            return $http
                .post('/api/adminusers/edit-user', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning user data", result);
                });
        }

        function postaddUser(userData) {
            var data = { userId: null, user: userData.user };

            return $http
                .post('/api/adminusers/add-user', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning branch closing or opening data", result);
                });
        }
        
        function postWarnExpiringUser(userId) {
            return $http
                .post('/api/adminusers/warn-expiring-user', null, { params: { userId: userId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error warning expiring user", result);
                });
        }

        function editUsersController($scope, $state, Dialogger, userId, $uibModalInstance, $log) {
            $scope.savingItem = false;
            $scope.saveChanges = saveChanges;
            $scope.cancel = cancel;
            $scope.isEditing = userId != null;
            $scope.heading = $scope.isEditing ? "Edit" : "Add";

            $scope.toggleSelection = function (roleId) {
                var idx = _.indexOf($scope.criteria.roleIds, roleId);
                if (idx > -1) { // is currently selected
                    $scope.criteria.roleIds.splice(idx, 1);
                } else { // is newly selected
                    $scope.criteria.roleIds.push(roleId);
                }
            };

            $scope.roles = [];
            $scope.autoRoles = [];
            $scope.rolesReady = false;
            $scope.criteria = {
                accountStatusName: "CHANGE_PASSWORD",
                userId: null,
                loginId: null,
                firstName: null,
                lastName: null,
                districtId: null,
                emailAddress: null,
                failedLoginCount: null,
                lastFailedLoginDate: null,
                isExternal: false,
                roleIds: []
            };
            $scope.userReady = userId == null;

            $scope.findUsers = findUsers;

            $scope.setAdUser = setAdUser;

            activate();

            function activate() {
                service.getRoles()
                    .then(function (data) {
                        $scope.roles = _.filter(data, ["isAuto", false]);
                        $scope.autoRoles = _.filter(data, "isAuto");
                        $scope.rolesReady = true;
                    });

                if (userId != null) {
                    service.getUserById(userId)
                        .then(function (data) {
                            $scope.criteria = data;
                            $scope.userReady = true;
                            $log.info("userReady", $scope.userReady);
                        });
                }

                $scope.$watchGroup(["criteria.firstName", "criteria.lastName"],
                    function (newValues, oldValues) {
                        //if ($scope.criteria.isExternal && newValues != null && _.isArray(newValues) && newValues.length > 1 && (newValues[0] && newValues[1]) && newValues[0].length > 0 && newValues[1].length > 0) {
                        //    $scope.findingUserName = true;
                        //    service.getUsername(newValues[0], newValues[1])
                        //        .then(function (data) {
                        //            $scope.criteria.loginId = data;
                        //            $scope.findingUserName = false;
                        //        });
                        //}
                    });

                //$scope.$watch("criteria.isExternal", function (newValue, oldValue) {
                //    if (newValue === false && oldValue == true)
                //       $scope.criteria.loginId = ""; //reset loginId to ensure user hasn't modified it
                //});
            }

            function saveChanges() {
                $scope.savingItem = true;
                $uibModalInstance.close({ user: $scope.criteria, userId: userId }); //, feedbackType: $scope.feedbackType });
            }

            function cancel() {
                $uibModalInstance.dismiss("cancel");
            }

            function findUsers(val) {
                return service
                    .searchForUser(val)
                    .then(function (data) {
                        return data;
                    });
            }

            function setAdUser($model) {
                $scope.criteria.loginId = $model.loginId;
                $scope.criteria.firstName = $model.firstName;
                $scope.criteria.lastName = $model.lastName;
                $scope.criteria.emailAddress = $model.emailAddress;
                $scope.criteria.accountStatusName = "NORMAL";
            }
        }

        function updateMenuLayout(userId, menuLayoutId) {
            var data = { userId: userId, menuLayoutId: menuLayoutId };
            return $http
                .post('/api/adminusers/update-menulayout-id', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error updating user menu layout id", result);
                });
        }

        function getLQUpdateStatusSummary(quarterEndDateString) {
            return $http
                .get('/api/admin/getLQValsUpdateStatus', { params: { qtrEndDt: quarterEndDateString } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting LQ values update status", result);
                });
        }

        function getOutdatedLQReport(quarterEndDateString) {
            var data = { QuarterEndDate: quarterEndDateString }
            return $http
                .post('/api/admin/getInstsWithOutdatedLQVals', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting report of institutions with outdated LQ data", result);
                });
        }

        function updateLQValsFromNIC(quarterEndDate) {
            var data = { QuarterEndDate: quarterEndDate }
            return $http
                .post('/api/admin/updateInstLQVals', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error updating LQ data", result);
                });
		}

		function getInstTypeValidationReport() {
			return $http
				.post('/api/admin/validateInstEntityTypes')
				.then(function Success(result) {
					return result.data;
				}, function Failure(result) {
					$log.error("Error validating institution type", result);
				});
		}


		

        //function updateLQValsFromNIC(quarterEndDate) {
        //    var data = { lqEndDateString: quarterEndDate };
        //    return $http
        //        .post('/api/admin/postUpdateInstLQVals', data)
        //        .then(function Success(result) {
        //            return result.data;
        //        }, function Failure(result) {
        //            $log.error("Error updating LQ values from NIC", result);
        //        });
        //}

        

        

    }
})();
;
(function () {
    "use strict";

    angular
        .module("app")
        .controller("AdminUsersController", AdminUsersController);

    AdminUsersController.$inject = ["$scope", '$rootScope', "$q", "AdminService", "Dialogger", "toastr", "$uibModal", "$log", "$timeout", "$state", "$cookies"];

    function AdminUsersController($scope, $rootScope, $q, AdminService, Dialogger, toastr, $uibModal, $log, $timeout, $state, $cookies) {
        $scope.roles = [];
        $scope.rolesReady = false;
		$scope.users = [];
		$scope.invalidUsers = [];
        $scope.usersReady = false;
        $scope.statuses = [];
        $scope.statusesReady = false;
        $scope.deleteUser = deleteUser;
        $scope.resetUser = resetUser;
        $scope.unlockUser = unlockUser;
        $scope.enableUser = enableUser;
        $scope.disableUser = disableUser;
        $scope.editUser = editUser;
        $scope.openAddUserForm = addUser;
        $scope.copyEmailsForm = copyEmails;
		$scope.findInactiveNetUsers = findInactiveNetUsers;
		$scope.userAccountWorkComplete = true;
		$scope.generateRoleReport = generateRoleReport;
		$scope.showSpinner = showSpinner;
		$scope.startRptGen = startRptGen;
		$scope.startRptGen = startRptGen;
        $scope.checkIfRptDone = checkIfRptDone;
        $scope.emails = null;
        $scope.notifiedExpiringUsers = [];
        $scope.currentDate = new Date();
        $scope.expireWarningDate = $scope.currentDate + 60;
        $scope.userExpirationStatus = userExpirationStatus;
        $scope.warnExpiringUser = warnExpiringUser;
        

        activate();

        function activate() {
            $q.all([AdminService.getRoles(), AdminService.getAccountStatuses()])
                .then(function (allResults) {
                    $scope.roles = allResults[0];
                    $scope.rolesReady = true;

                    $scope.statuses = allResults[1];
                    $scope.statusesReady = true;

                    AdminService
                        .getUserListData()
						.then(function (data) {							
                            $scope.users = data;
                            setRoleNames($scope.users);
                            $scope.usersReady = true;
                        });                    
                });
        }


        function userExpirationStatus(userExpirationDtString, accountStatusId) {

            var currentDate = new Date();
            var expireDate = new Date(userExpirationDtString);
            var expireSoonDate = new Date();
            expireSoonDate.setDate(expireSoonDate.getDate() + 60);
            if (expireDate < currentDate) {
                return 1;
            }
            else if (expireDate < expireSoonDate && accountStatusId == 1) {  // expires soon AND account status is normal
                return 2;
            }
            else {
                return 0;
            }       
        }
        
     
		function generateRoleReport() {
			$state.go("root.adv.quarterlydata.rolemembers");
		}

        function setRoleNames(users) {
            var userArray = _.isArray(users) ? users : [users];

            for (var i = 0; i < userArray.length; i++) {
                userArray[i].roleNames = [];
                for (var j = 0; j < $scope.roles.length; j++) {
                    if (_.indexOf(userArray[i].roleIds, $scope.roles[j].id) > -1) {
                        userArray[i].roleNames.push($scope.roles[j].name);
                    }
                }
                userArray[i].roles = _.join(userArray[i].roleNames, ", ");
            }
        }

        function deleteUser(user) {
            user.isTargeted = true;

            var confirmDialog = Dialogger
                .confirm("Are you sure you want to delete user " +
                    user.firstName + " " + user.lastName + "?");

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    AdminService
                        .deleteUser(user.userId)
                        .then(function (data) {
                            if (!data.errorFlag) {
                                toastr.success("Account for " + user.firstName + " " + user.lastName + " was deleted successfully!");
                                var index = $scope.users.indexOf(user);
                                if (index !== -1) {
                                    $scope.users.splice(index, 1);
                                }
                            } else {
                                toastr.error("There was an unexpected error.",
                                    data
                                    .messageTextItems[0] ||
                                    "Please try again or contact support. Sorry about that.");
                            }
                            user.isTargeted = false;
                        });
                } else
                    user.isTargeted = false;
            });
        }

        function resetUser(user) {
            user.isTargeted = true;
            var confirmDialog = Dialogger.confirm("Are you sure you want to reset the password for " + user.firstName + " " + user.lastName + "?");

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    AdminService
                        .postresetPassword(user.userId)
                        .then(function (data) {
                            if (!data.errorFlag) {
                                toastr.success("Password for " + user.firstName + " " + user.lastName + " was reset successfully!");
                                angular.extend(user, data.user);
                            } else {
                                toastr.error("There was an unexpected error.",
                                    data
                                    .messageTextItems[0] ||
                                    "Please try again or contact support. Sorry about that.");
                            }
                            user.isTargeted = false;
                        });
                } else
                    user.isTargeted = false;
            });
        }

        function warnExpiringUser(user) {
            var confirmDialog = Dialogger.confirm("Are you sure you want to send a warning email?");

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    AdminService
                        .postWarnExpiringUser(user.userId)
                        .then(function (data) {
                            if (!data.errorFlag) {
                                toastr.success("Email sent");
                                $rootScope.accountsExpiringSoonCount = $rootScope.accountsExpiringSoonCount - 1;
                                user.expirationWarningSent = true;
                            } else {
                                toastr.error("There was an error sending email.");
                            }
                        });
                } else
                    user.isTargeted = false;
            });
        }

        function hasExpiringUserBeenWarned(userId) {
            return $scope.notifiedExpiringUsers.includes(userId);
        }

        function unlockUser(user) {
            user.isTargeted = true;
            AdminService
                .postunlockUser(user.userId)
                .then(function (data) {
                    if (!data.errorFlag) {
                        toastr.success("Account for " + user.firstName + " " + user.lastName + " unlocked successfully!");
                        angular.extend(user, data.user);
                    } else {
                        toastr.error("There was an unexpected error.",
                            data.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
                    }
                    user.isTargeted = false;
                });
        }

        function enableUser(user) {
            user.isTargeted = true;
            AdminService
                .postEnableUser(user.userId)
                .then(function (data) {
                    if (!data.errorFlag) {
                        toastr.success("Account for " + user.firstName + " " + user.lastName + " has been enabled!");
                        angular.extend(user, data.user);
                    } else {
                        toastr.error("There was an unexpected error.",
                            data.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
                    }
                    user.isTargeted = false;
                });
        }

        function disableUser(user) {
            user.isTargeted = true;
            AdminService
                .postDisableUser(user.userId)
                .then(function (data) {
                    if (!data.errorFlag) {
                        toastr.success("Account for " + user.firstName + " " + user.lastName + " has been disabled!");
                        angular.extend(user, data.user);
                    } else {
                        toastr.error("There was an unexpected error",
                            data.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
                    }
                    user.isTargeted = false;
                });
        }

        function editUser(user) {
            user.isTargeted = true;
            AdminService.addOrEditUser(user.userId)
                .then(function (updatedUser) {
                    user.isTargeted = false;
                    if (updatedUser) {
                        setRoleNames(updatedUser);
                        angular.extend(user, updatedUser);
                        toastr.success("User " + user.firstName + " " + user.lastName + " has been updated!");
                    }
                });
        }

        function addUser() {
            AdminService.addOrEditUser()
                .then(function (newUser) {
                    if (newUser && newUser.userId) {
                        setRoleNames(newUser);
                        $scope.users.push(newUser);
                        toastr.success("User " + newUser.firstName + " " + newUser.lastName + " has been created!");
                    }
                });
		}
        function copyEmails() {

           
            $uibModal.open({
                animation: true,
                modal: true,
                backdrop: false,
                size: 'lg',
                templateUrl: 'AppJs/advanced/admin/views/emails.html',
                controller: 'AdminEmailsController'
            });
  
        }
		function showSpinner() {
			$scope.userAccountWorkComplete = false;
		}

		function startRptGen() {
			$scope.showSpinner();
			$timeout(function () {
				$scope.checkIfRptDone();
			}, 100);
		}

		function checkIfRptDone() {
			var rptDoneCookieVal = $cookies.get("rptdone");
			if (!rptDoneCookieVal || rptDoneCookieVal == '0') {
				$timeout(function () {
					$scope.checkIfRptDone();
				}, 500);
			}
			else {
				$cookies.remove("rptdone");
				$scope.userAccountWorkComplete = true;
			}
			return;
		}

		function findInactiveNetUsers() {
			$scope.userAccountWorkComplete = false; 
			AdminService.getInactiveNetworkUsers()
				.then(function (inactiveUsers) {
					if ($scope.users && inactiveUsers) {
						$scope.invalidUsers = inactiveUsers;
						var inactiveUserLogins = [];
						// create position index of where each loginId is in the inactiveUsers array
						for (var i = 0; i < inactiveUsers.length; i++) {
							inactiveUserLogins[inactiveUsers[i].loginId] = i;
						}
						// loop through users and apply extra data to each inactive user
						for (var i = 0; i < $scope.users.length; i++) {
							if (inactiveUserLogins[$scope.users[i].loginId]) {
								$scope.users[i].userAccountADStatus = inactiveUsers[inactiveUserLogins[$scope.users[i].loginId]];
							}
						}

						// sort the inactives to the top
						if (inactiveUsers.length > 0) {
							$timeout(function () {
								if (!$('#ADStatusInfoCol').hasClass('st-sort-ascent')) {
									document.getElementById('ADStatusInfoCol').click();
								}
								$scope.userAccountWorkComplete = true;
							}, 0);
						}
						else {
							$scope.userAccountWorkComplete = true;
							toastr.error("No invalid users found.");
						}
					}
					else {
						$scope.userAccountWorkComplete = true; 
					}
				});			
		}		
    }
})();


(function () {
    "use strict";

    angular
        .module("app")
        .controller("AdminEditUsersController", AdminEditUsersController);

    AdminEditUsersController.$inject = ["$scope", "$state", "AdminService", "Dialogger", "toastr", "userId", "$uibModalInstance", "$log"];

    function AdminEditUsersController($scope, $state, AdminService, Dialogger, toastr, userId, $uibModalInstance, $log) {
        $scope.savingItem = false;
        $scope.saveChanges = saveChanges;
        $scope.cancel = cancel;
        $scope.isEditing = userId != null;
        $scope.heading = $scope.isEditing ? "Edit" : "Add";

        $scope.toggleSelection = function (roleId) {
            if (_.indexOf($scope.criteria.roleIds, roleId) > -1) { // is currently selected
                $scope.criteria.roleIds.splice(idx, 1);
            } else { // is newly selected
                $scope.criteria.roleIds.push(roleId);
            }
        };

        $scope.roles = [];
        $scope.autoRoles = [];
        $scope.rolesReady = false;
        $scope.criteria = {
            accountStatusName: "CHANGE_PASSWORD",
            userId: null,
            loginId: null,
            firstName: null,
            lastName: null,
            districtId: null,
            emailAddress: null,
            failedLoginCount: null,
            lastFailedLoginDate: null,
            doNotEmail: null,
            roleIds: []
        };
        $scope.userReady = userId != null;

        activate();

        function activate() {
            AdminService.getRoles()
                .then(function (data) {
                    $scope.roles = _.filter(data, ["isAuto", false]);
                    $scope.autoRoles = _.filter(data, "isAuto");
                    $scope.rolesReady = true;
                });

            if (userId != null) {
                AdminService.getUserById(userId)
                    .then(function (data) {
                        $scope.criteria = data;
                        $scope.userReady = true;
                        $log.info("userReady", $scope.userReady);
                    });
            }
        }

        function saveChanges() {
            $scope.savingItem = true;
            $uibModalInstance.close({ user: $scope.criteria, userId: userId }); //, feedbackType: $scope.feedbackType });
        }

        function cancel() {
            $uibModalInstance.dismiss("cancel");
        }
    }
})();

(function () {
    "use strict";

    angular
        .module("app")
        .controller("AdminEmailsController", AdminEmailsController);

    AdminEmailsController.$inject = ["$scope", "$state", "AdminService", "Dialogger", "toastr", "$uibModalInstance", "$log"];

    function AdminEmailsController($scope, $state, AdminService, Dialogger, toastr, $uibModalInstance, $log) {
        $scope.savingItem = false;
        $scope.cancel = cancel;
        $scope.usersReady = false;

        activate();

        function activate() {
            AdminService
                .getCaseWorkerEmails()
                .then(function (data) {
                    $scope.emails = "";
                    for (var i = 0; i < data.length; i++) {
                        $scope.emails += " " + data[i] + ";";
                    }
                                       
                    //var txtbox = document.getElementById("clipboardCopyHolder");
                    //txtbox.value = $scope.emails;
                    ////document.body.appendChild(txtbox);
                    //txtbox.select();
                    //txtbox.setSelectionRange(0, 99999); /*For mobile devices*/
                    //document.execCommand("copy");
                   
                    $scope.usersReady = true;
                });
        }

        function cancel() {
            $uibModalInstance.dismiss("cancel");
        }
    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
        .factory('AdvancedNewsService', AdvancedNewsService);

    AdvancedNewsService.$inject = ['$http', '$log', '$q', '$cookies'];

    function AdvancedNewsService($http, $log, $uibModal, $q, $cookies) {

        var cookie_key = "dismissed-news";

        var service = {
            get: getNewsById,
            query: getNewsByChannel,
            post: postNews,
            delete: deleteNews,
            getDismissedNewsIds: getNewsIds,
            dismissByNewsId: dismissNewsItem,
            parseNotes: splitIntoNotes,
            getChannels: getChannelsFromJson,
            format: formatPlainText,
            patch: makeActive
        };

        return service;

        /////////////////////////////////

		function getNewsById(id, admMode) {
			return $http.get(admMode ? '/api/news/AdmGetNewsItem' : '/api/news/GetNewsItem', { params: { newsId: newsId } })
                .then(function Success(result) {
    
                    return result.data;
                 
                }, function Failure(result) {
                    $log.error("Error returning news data", result);
                });
        }

        function getNewsByChannel(channel, limit, showAll, admMode) {
			return $http.get(admMode ? '/api/news/AdmGetNews' : '/api/news/GetNews', { params: { channel: channel, limit: limit, showAll: showAll } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning news data", result);
                });
        }

        function postNews(data) {
            return $http.post('/api/news/SaveNews', data)
                .then(function Success(result) {
                    return result;
                }, function Failure(result) {
                    $log.error("Error updating news data", result);
                });
        }

        function deleteNews(id) {
            return $http.delete('/api/news/DeleteNews', { params: { newsId: id } })
                .then(function Success(result) {
                    return result;
                }, function Failure(result) {
                    $log.error("Error deleing news data", result);
                });
        }


        function getNewsIds() {

            if ($cookies) {
                var cookie_value = $cookies.get(cookie_key),
                    newsIds = cookie_value ? JSON.parse(cookie_value) : [];

                if (!angular.isArray(newsIds)) newsIds = [];

             
            }

            return newsIds;

        }

        function saveNewsIds(newsIds) {
            var expiry = new Date();
            expiry.setDate(expiry.getDate() + 10000);
            $cookies.put(cookie_key, JSON.stringify(newsIds), { expires: expiry });
        }

        function dismissNewsItem(newsId) {
            var newsIds = getNewsIds();
            newsIds.push(newsId);
            saveNewsIds(newsIds);
        }

        function splitIntoNotes(text) {
            if (text == '')
                return [];

            return text.split('\n');
        }

        function formatPlainText(text) {
            return text.replace(/[\n\r]/g, '<br />');
        }

        function getChannelsFromJson() {
           return $http.get('/_jsonData/NewsChannels.json')
                .then(function Success(result) {
                    return result.data.channels;
                }, function Failure(result) {
                    $log.error("Error returning channel data", result);
                });
        }

        function makeActive(id) {

            return $http.post('/api/news/PostActive', id)
                .then(function Success(result) {
                    return result;
                }, function Failure(result) {
                    $log.error("Error making news active", result);
                });

        }
    }
})();

const NewsChannelType = {
    NewsFeed: 1,
    ReleaseNotes: 2,
    ContentArea: 3
};
(function () {
    'use strict';

    angular
        .module('app')
        .controller('EditNewsController', EditNewsController);

    EditNewsController.$inject = ['$scope', '$state', '$log', '$uibModal', 'toastr', '$sce', '$uibModalInstance', 'news', 'AdvancedNewsService'];

    function EditNewsController($scope, $state, $log, $uibModal, toastr, $sce, $uibModalInstance, news, AdvancedNewsService) {

        $scope.criteria = {};
        $scope.channels = [];
        $scope.previewMode = false;

        activate();

        function activate() {

            AdvancedNewsService.getChannels().then(function (channels) {
                $scope.channels = channels;
            });
            $scope.criteria = $.extend({}, news);

        }

        $scope.isContentActive = function () {
            return $scope.criteria !== null ? $scope.criteria.isPublic : false;
        }

        $scope.setContentActive = function () {
            $scope.criteria.isPublic = $scope.criteria !== null ? !$scope.criteria.isPublic : true;
        }


        $scope.saveChanges = function () {

            var chosenChannel = _.find($scope.channels, { 'key': $scope.criteria.channel });

            $scope.criteria.isAdvanced = chosenChannel.isAdvanced;
            $uibModalInstance.close($scope.criteria);
        };

        $scope.cancel = function () {
            $uibModalInstance.close('cancel');
        };


        $scope.togglePreview = function () {
            $scope.previewMode = !$scope.previewMode;
        };


        $scope.getPreview = function () {

         
            var chosenChannel = _.find($scope.channels, { 'key': $scope.criteria.channel });

            if (chosenChannel != null) {
                switch (chosenChannel.type) {
                    case 1: {
                        return AdvancedNewsService.format($scope.criteria.body);
                    }
                    case 2: {
                        var notes = AdvancedNewsService.parseNotes($scope.criteria.body);

                        return "<b>" + $scope.criteria.title + "</b><br/><ul>" + _.join(_.map(notes, function (note) { return "<li>" + note + "</li>"; }), '') + "</ul>";
                    }
                    case 3: {
                        return AdvancedNewsService.format($scope.criteria.body);
                    }
                }
            }


        };
       
    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('fileUploadService', fileUploadService);

    fileUploadService.$inject = ['$http', '$q', '$log'];

    function fileUploadService($http, $q, $log) {
        var service = {
            readFileAsync: readFileAsync
        };

        return service;
        ////////////////


        function readFileAsync(file) {
            var deferred = $q.defer();

            //fileReader = new FileReader();
            var reader = new FileReader();


            reader.readAsText(file);

            var csvfile;

            reader.onload = function (e) {
                csvfile = e.target.result;
                var data = {
                    csvdata: csvfile
                };

                return $http.post('/api/advinstitutions/batch-GeoCode-Upload',  data )
                    .then(function Success(result) {
                        deferred.resolve(result.data);
                    }, function Failure(result) {
                        $log.error("Error processing the GEOCode bulk upload", result);
                    });

            };

            return deferred.promise;

            
           


              
        }

        

    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('geoCodeBulkUploadController', geoCodeBulkUploadController);

    geoCodeBulkUploadController.$inject = ['$rootScope', '$scope', 'fileUploadService', '$q', '$log', 'toastr'];

    function geoCodeBulkUploadController($rootScope, $scope, fileUploadService, $q, $log, toastr) {

        $scope.fileprocessed = false;

        activate();

        function activate() {
        }




        $scope.fileInputContent = "";


        $scope.onFileUpload = function (element) {
                
                var file = element.files[0];
                $scope.fileprocessed = false;
                fileUploadService.readFileAsync(file).then(function (results) {
                    $scope.results = results;

                    if (results && results != null) {
                        if (results.errorFlag)
                        {
                            $scope.fileprocessed = false;
                            if (results.messageTextItems.length > 0) {
                                for (var i = 0; i < results.messageTextItems.length; i++) {
                                    toastr.error(results.messageTextItems[i]);
                                }
                            }
                        }
                        else
                        {
                            $scope.affectedItemCount = results.affectedItemCount;
                            $scope.fileprocessed = true;
                            $scope.resultsInfo = results.resultObject;

                            if (results.messageTextItems.length > 0) {
                                for (var i = 0; i < results.messageTextItems.length; i++) {
                                    toastr.error(results.messageTextItems[i]);
                                }
                            }

                        }
                        
                    }

                     
                });
                
                   
            
        };

        

         
    

    }
})();

;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('HHIScenarioValidation', HHIScenarioValidation);

    HHIScenarioValidation.$inject = ['$http', '$log', '$uibModal',  'AdvMarketsService'];

    function HHIScenarioValidation($http, $log, $uibModal, AdvMarketsService) {
        var service = {
            hhiScenario1: HHIScenario1,
            hhiScenario2: HHIScenario2,
            hhiScenario3: HHIScenario3,
            hhiScenario4: HHIScenario4
        };

        return service;
        ////////////////


        function HHIScenario1() {

            var TargetOrg;
            var BuyerOrg;
            var ResultOrg;
            var OtherOrg;
            
            var data = {
                marketID: 13020,
                msaID:  null,
                stateId:  null ,
                custommarkets: null,
                blnbankandthrift: true,
                buyer: 1131787,
                targets: '1074156',
                branches: null,
                treatTHCBuyerAsBHC: false
            };


            var HHIResult = {
                scenarioNum: 1,
                title: 'BHC with only one bank to acquire BHC with only one bank',
                dataValidation: '',
                uiValidation: 'n/a',
                message: ''
            };

            AdvMarketsService
                       .getProformaHHI(data)
                       .then(function (result) {

                           if (result.validationMessage) {
                               //there was an issue or some input needed
                               HHIResult.message = result.validationMessage;
                               HHIResult.dataValidation = 'Failed';
                           }
                           else
                           {
                               //we have a full object now verify
                               //populate the org list
                               TargetOrg = result.proFormReportData.targetProformaItems;
                               BuyerOrg = result.proFormReportData.buyerProformaItems;
                               ResultOrg = _.filter(result.proFormReportData.resultingOrgProformaItems, function (e) { return e.rssdid == 1131787 || _.filter(e.childInst, function (c) { return c.rssdid == 1131787 }).length > 0 });
                               OtherOrg = result.proFormReportData.otherOrgProformaItems;

                               //validate the numbers
                               //validate the hhi values
                               HHIResult.dataValidation = 'Success';


                               if (result.hhiPostMergerUnWeightedDeposits != 4887.519)
                               {
                                   HHIResult.message = HHIResult.message + " Post Merger unWeighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }
                                
                               if (result.hhiPostMergerWeightedDeposits != 4854.5495)
                               {
                                   HHIResult.message = HHIResult.message + " Post Merger Weighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }
                                
                               if (result.hhiPreMergerUnWeightedDeposits != 4887.519)
                               {
                                   HHIResult.message = HHIResult.message + " Pre Merger unWeighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }
                               
                               if (result.hhiPreMergerWeightedDeposits != 4854.5495)
                               {
                                   HHIResult.message = HHIResult.message + " Pre Merger Weighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }


                               
                           }
                       });

            return HHIResult;

        }

        function HHIScenario2() {
            var TargetOrg;
            var BuyerOrg;
            var ResultOrg;
            var OtherOrg;

            var data = {
                marketID: 29235,
                msaID:  null,
                stateId:  null,
                custommarkets: null,
                blnbankandthrift: true,
                buyer: 1049341,
                targets: '2107707',
                branches: null,
                treatTHCBuyerAsBHC: false
            };


            var HHIResult = {
                scenarioNum: 2,
                title: 'BHC to acquire BHC with multiple banks',
                dataValidation: '',
                uiValidation: 'n/a',
                message: ''
            };

            AdvMarketsService
                       .getProformaHHI(data)
                       .then(function (result) {

                           if (result.validationMessage) {
                               //there was an issue or some input needed
                               HHIResult.message = result.validationMessage;
                               HHIResult.dataValidation = 'Failed';
                           }
                           else {
                               //we have a full object now verify
                               //populate the org list
                               TargetOrg = result.proFormReportData.targetProformaItems;
                               BuyerOrg = result.proFormReportData.buyerProformaItems;
                               ResultOrg = _.filter(result.proFormReportData.resultingOrgProformaItems, function (e) { return e.rssdid == 1131787 || _.filter(e.childInst, function (c) { return c.rssdid == 1131787 }).length > 0 });
                               OtherOrg = result.proFormReportData.otherOrgProformaItems;

                               //validate the numbers
                               //validate the hhi values
                               HHIResult.dataValidation = 'Success';


                               if (result.hhiPostMergerUnWeightedDeposits != 52726.011) {
                                   HHIResult.message = HHIResult.message + " Post Merger unWeighted Deposits not correct , " + result.hhiPostMergerUnWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPostMergerWeightedDeposits != 50509.0135) {
                                   HHIResult.message = HHIResult.message + " Post Merger Weighted Deposits not correct, " + result.hhiPostMergerWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPreMergerUnWeightedDeposits != 52726.011) {
                                   HHIResult.message = HHIResult.message + " Pre Merger unWeighted Deposits not correct, " + result.hhiPreMergerUnWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPreMergerWeightedDeposits != 50509.0135) {
                                   HHIResult.message = HHIResult.message + " Pre Merger Weighted Deposits not correct, " + result.hhiPreMergerWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }



                           }
                       });

            return HHIResult;
        }

        function HHIScenario3() {
            var TargetOrg;
            var BuyerOrg;
            var ResultOrg;
            var OtherOrg;

            var data = {
                marketID: 13020,
                msaID: null,
                stateId: null,
                custommarkets: null,
                blnbankandthrift: true,
                buyer: 1131787,
                targets: '1134313',
                branches: null,
                treatTHCBuyerAsBHC: false
            };


            var HHIResult = {
                scenarioNum: 3,
                title: 'BHC to acquire SLHC with only one thrift',
                dataValidation: '',
                uiValidation: 'n/a',
                message: ''
            };

            AdvMarketsService
                       .getProformaHHI(data)
                       .then(function (result) {

                           if (result.validationMessage) {
                               //there was an issue or some input needed
                               HHIResult.message = result.validationMessage;
                               HHIResult.dataValidation = 'Failed';
                           }
                           else {
                               //we have a full object now verify
                               //populate the org list
                               TargetOrg = result.proFormReportData.targetProformaItems;
                               BuyerOrg = result.proFormReportData.buyerProformaItems;
                               ResultOrg = _.filter(result.proFormReportData.resultingOrgProformaItems, function (e) { return e.rssdid == 1131787 || _.filter(e.childInst, function (c) { return c.rssdid == 1131787 }).length > 0 });
                               OtherOrg = result.proFormReportData.otherOrgProformaItems;

                               //validate the numbers
                               //validate the hhi values
                               HHIResult.dataValidation = 'Success';


                               if (result.hhiPostMergerUnWeightedDeposits != 4887.519) {
                                   HHIResult.message = HHIResult.message + " Post Merger unWeighted Deposits not correct , " + result.hhiPostMergerUnWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPostMergerWeightedDeposits != 4887.519) {
                                   HHIResult.message = HHIResult.message + " Post Merger Weighted Deposits not correct, " + result.hhiPostMergerWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPreMergerUnWeightedDeposits != 4887.519) {
                                   HHIResult.message = HHIResult.message + " Pre Merger unWeighted Deposits not correct, " + result.hhiPreMergerUnWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPreMergerWeightedDeposits != 4854.5495) {
                                   HHIResult.message = HHIResult.message + " Pre Merger Weighted Deposits not correct, " + result.hhiPreMergerWeightedDeposits;
                                   HHIResult.dataValidation = 'Failed';
                               }



                           }
                       });

            return HHIResult;
        }

        function HHIScenario4(id) {
            var TargetOrg;
            var BuyerOrg;
            var ResultOrg;
            var OtherOrg;

            var data = {
                marketID: 13020,
                msaID: null,
                stateId: null,
                custommarkets: null,
                blnbankandthrift: true,
                buyer: 1131787,
                targets: '233031',
                branches: null,
                treatTHCBuyerAsBHC: false
            };


            var HHIResult = {
                scenarioNum: 4,
                title: 'BHC to acquire controlled bank',
                dataValidation: '',
                uiValidation: 'n/a',
                message: ''
            };

            AdvMarketsService
                       .getProformaHHI(data)
                       .then(function (result) {

                           if (result.validationMessage) {
                               //there was an issue or some input needed
                               HHIResult.message = result.validationMessage;
                               HHIResult.dataValidation = 'Failed';
                           }
                           else {
                               //we have a full object now verify
                               //populate the org list
                               TargetOrg = result.proFormReportData.targetProformaItems;
                               BuyerOrg = result.proFormReportData.buyerProformaItems;
                               ResultOrg = _.filter(result.proFormReportData.resultingOrgProformaItems, function (e) { return e.rssdid == 1131787 || _.filter(e.childInst, function (c) { return c.rssdid == 1131787 }).length > 0 });
                               OtherOrg = result.proFormReportData.otherOrgProformaItems;

                               //validate the numbers
                               //validate the hhi values
                               HHIResult.dataValidation = 'Success';


                               if (result.hhiPostMergerUnWeightedDeposits != 4887.519) {
                                   HHIResult.message = HHIResult.message + " Post Merger unWeighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPostMergerWeightedDeposits != 4854.5495) {
                                   HHIResult.message = HHIResult.message + " Post Merger Weighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPreMergerUnWeightedDeposits != 4887.519) {
                                   HHIResult.message = HHIResult.message + " Pre Merger unWeighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }

                               if (result.hhiPreMergerWeightedDeposits != 4854.5495) {
                                   HHIResult.message = HHIResult.message + " Pre Merger Weighted Deposits not correct";
                                   HHIResult.dataValidation = 'Failed';
                               }



                           }
                       });

            return HHIResult;
        }

        

    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('HHIScenarioValidationController', HHIScenarioValidationController);

    HHIScenarioValidationController.$inject = ['$rootScope', '$scope', '$state', 'uiUploader', '$log', '$http', 'HHIScenarioValidation'];

    function HHIScenarioValidationController($rootScope, $scope, $state, uiUploader, $log, $http, HHIScenarioValidation) {
        

       
         

        activate();

        function activate() {

            //start processing the Scenarios
            var Hresult;
            var Hresult2;

            var scenarioResults = [];

            scenarioResults.push(HHIScenarioValidation.hhiScenario1());

            scenarioResults.push(HHIScenarioValidation.hhiScenario2());

            scenarioResults.push(HHIScenarioValidation.hhiScenario3());

            scenarioResults.push(HHIScenarioValidation.hhiScenario4());


            $scope.scenarioResults = scenarioResults;

        }
        
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('LQValsUpdateController', LQValsUpdateController);

    LQValsUpdateController.$inject = ["$scope", "AdminService", "Dialogger", "toastr", "$uibModal", "$log"];

    function LQValsUpdateController($scope, AdminService, Dialogger, toastr, $uibModal, $log) {
        $scope.LoadNonUpdatedInstsReport = LoadNonUpdatedInstsReport;
        $scope.UpdateLQValuesFromNIC = UpdateLQValuesFromNIC;
        $scope.SwitchQuarter = SwitchQuarter;
        $scope.quarterOptions = [];
        $scope.GetQuarterOption = GetQuarterOption;

        activate();

        function activate() {
            $scope.currentYear = new Date().getFullYear();
            $scope.currentQuarter = Math.floor(((new Date()).getMonth()) / 3);      // quarter = 0 - 3
            $scope.quarterOptions = getQuarterSelections($scope.currentQuarter);
            $scope.LQUpdateStatus = null;
            populateStatusCounts();
        }


        function LoadNonUpdatedInstsReport() {
            if ($scope.LQUpdateStatus && $scope.LQUpdateStatus.numRemaining > 500)  // make 500 the threshold for defining a "large" dataset
            {
                var confirmDialog = Dialogger.confirm("WARNING: This report contains a large number of institutions. It may take several minutes to complete. Are you sure that you want to continue? <br /><br />Click OK to generate the report.");
                confirmDialog.then(function (confirmed) {
                    if (confirmed) {
                        loadNonUpdatedInstsReportData();
                    }
                });
            }
            else 
            {
                loadNonUpdatedInstsReportData();
            }
        }

        function loadNonUpdatedInstsReportData()
        {
            var quarterEnd = !$scope.LQUpdateStatus ? '' : $scope.LQUpdateStatus.lqDateString;
            $scope.loadState = 'loading';
            AdminService.getOutdatedLQReport(quarterEnd).then(function (result) {
                $scope.loadState = 'loaded';
                if (result && result != null) {
                    $scope.InstsWithoutLQUpdate = result;
                }
            });
        }

        function SwitchQuarter()
        {
            var newLQDateString = $scope.LQUpdateStatus.lqDateString;
            populateStatusCounts();
        }

        function GetQuarterOption(quarterNum) {
            if ($scope.quarterOptions && $scope.quarterOptions.length == 0) {
                getQuarterSelections();                
            }

            if (quarterNum < 0 || quarterNum > 3) { quarterNum = 0;}
            return $scope.quarterOptions[quarterNum]
        }

        function UpdateLQValuesFromNIC() {
            var confirmDialog = Dialogger
                .confirm("Are you sure you want to update ALL institution LQ values from NIC?");

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    $scope.InstsWithoutLQUpdate = null;
                    $scope.loadState = 'loading';
                    AdminService.updateLQValsFromNIC($scope.LQUpdateStatus.lqDateString).then(function (result) {
                        $scope.loadState = 'loaded';
                        if (result) {                            
                            populateStatusCounts(showNumRemainingDialog) // re-run the initial checks of updated inst counts.                            
                        }
                    });
                }
            });
        }

        function populateStatusCounts(callBackFunction) {
            $scope.loadState = 'loading';
            var quarterEnd = !$scope.LQUpdateStatus ? '' : $scope.LQUpdateStatus.lqDateString;
            AdminService.getLQUpdateStatusSummary(quarterEnd).then(function (result) {
                $scope.loadState = 'loaded';
                if (result && result != null) {
                    $scope.LQUpdateStatus = result;
                    if (callBackFunction) { callBackFunction(result); }
                }
            });
        }

        function getQuarterSelections(startingQuarter) {
            var thisYear = $scope.currentYear;
            var lastYear = thisYear - 1;
            // Q1 order as default
            var quarterOrder = ['12/31/' + lastYear,
                                 '9/30/'  + lastYear, 
                                 '6/30/'  + lastYear, 
                                 '3/31/'  + lastYear];

            // 0 based so this is Q2
            if (startingQuarter == 1) {
                quarterOrder = [ '3/31/' + thisYear,
                                 '12/31/' + lastYear,
                                 '9/30/' + lastYear,
                                 '6/30/' + lastYear];
            }
            else if (startingQuarter == 2) {  //Q3
                quarterOrder = [ '6/30/' + thisYear,
                                 '3/31/' + thisYear,
                                 '12/31/' + lastYear,
                                 '9/30/' + lastYear];
            }
            else if (startingQuarter == 3) {  //Q4
                quarterOrder = ['9/30/' + thisYear,
                                 '6/30/' + thisYear,
                                 '3/31/' + thisYear,
                                 '12/31/' + lastYear];                                 
            }

            return quarterOrder;            
        }

        function showNumRemainingDialog(lqStatusData)
        {
            Dialogger.alert(lqStatusData.numRemaining + ' institutions have NOT been updated. To view these institutions, Click the "Show Differing Items" button.');
        }
    }    
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('MissedBrClosingsController', MissedBrClosingsController);

    MissedBrClosingsController.$inject = ["$scope", "AdvInstitutionsService","AdvBranchesService", "Dialogger", "toastr", "$uibModal", "$log", "$state", "$window"];

    function MissedBrClosingsController($scope, AdvInstitutionsService, AdvBranchesService, Dialogger, toastr, $uibModal, $log, $state, $window) {
        $scope.LoadMissedClosings = LoadMissedClosings;
        $scope.isLoading = false;
        $scope.missedBrClosings = [];
        $scope.missedBrClosingsCopy = [];
        $scope.currentYear = new Date().getFullYear();
        $scope.showResults = false;

        $scope.startDate = "01/01/2023";
        $scope.endDate = "12/01/2023";
        $scope.currentQuarter = Math.floor(((new Date()).getMonth()) / 3);      // quarter = 0 - 3     

        activate();

        function activate() {
            
                       

            //populateStatusCounts();
        }

        function LoadMissedClosings() {
            if (!$scope.startDate || !$scope.endDate) {
                toastr.error('Start Date and End Date are required');
                return;
            }
            $scope.isLoading = true;
            $scope.showResults = false;
            AdvInstitutionsService.getFindOpenClosedBranches($scope.startDate, $scope.endDate).then(
                function (result) {
                    $scope.missedBrClosings = result;
                    $scope.missedBrClosingsCopy = $scope.missedBrClosings;
                    $scope.isLoading = false;
                    $scope.showResults = true;
                }
            )
        }

        $scope.showCloseMemo = function (objMemoLnk) {
            var dataObj = $(objMemoLnk)[0].missedClosing;
            var instRssd = dataObj.instRSSDId;
            var instCert = dataObj.fdicCert;
            var instName = dataObj.instName;
            var instAddress = dataObj.instAddress;
            var instCity = dataObj.instCity;
            var instCountyName = dataObj.instCountyName;
            var instCountyNum = dataObj.instCountyNum;
            var instState = dataObj.instState;
            var brUninum = dataObj.uninum;
            var brAddress = dataObj.address;
            var brCity = dataObj.cityName;
            var brState = dataObj.stateName;
            var brZip = dataObj.zipcode;
            var changeCodeDesc = 'Branch Closing';
            var brName = dataObj.branchName;
            var brCountyName = dataObj.countyName;
            var brCountyNum = dataObj.countyNum;
            var brServTypeCode = dataObj.servTypeCode;
            var brServTypeDesc = dataObj.servTypeDesc;
            var effDate = new Date(dataObj.effDate).toLocaleDateString('en-US');
            var procDate = new Date(dataObj.procDate).toLocaleDateString('en-US');
            var todaysDateStr = new Date().toLocaleDateString('en-US');
            var htmString = "<html><head><link href='/content/css/FdicClosingDataWindow.css' rel='stylesheet' /></head><body><h1>FDIC Branch Closing Data </h1>";
            htmString += "<p><strong>Generated: " + todaysDateStr + "</strong></p>";
            htmString += "<ul>";
            htmString += "<li class='standout'><span class='dataLabel'>EFF Date:</span>" + effDate + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>PROC Date:</span>" + procDate + "</li>";
            htmString += "<li><span class='dataLabel'>Institution RSSDId:</span> " + instRssd + "</li>";
            htmString += "<li><span class='dataLabel'>FDIC Certificate Num:</span>" + instCert + "</li>";
            htmString += "<li><span class='dataLabel'>Uninum:</span>" + brUninum + "</li>";
            htmString += "<li><span class='dataLabel'>&nbsp;&nbsp;</span>&nbsp;&nbsp;</li>";
            htmString += "<li class='standout'><span class='dataLabel'>Branch Name:</span>" + brName + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>Address:</span>" + brAddress + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>City:</span>" + brCity + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>County Name:</span>" + brCountyName + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>County Number:</span>" + brCountyNum + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>State:</span>" + brState + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>Zipcode:</span>" + brZip + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>Branch Serv Type Code:</span>" + brServTypeCode + "</li>";
            htmString += "<li class='standout'><span class='dataLabel'>Branch Serv Type Desc:</span>" + brServTypeDesc + "</li>";
            htmString += "<li><span class='dataLabel'>&nbsp;&nbsp;</span>&nbsp;&nbsp;</li>";
            htmString += "<li><span class='dataLabel'>Institution Name:</span>" + instName + "</li>";
            htmString += "<li><span class='dataLabel'>Institution Address:</span>" + instAddress + "</li>";
            htmString += "<li><span class='dataLabel'>Institution City:</span>" + instCity + "</li>";
            htmString += "<li><span class='dataLabel'>Institution County Name:</span>" + instCountyName + "</li>";
            htmString += "<li><span class='dataLabel'>Institution County Number:</span>" + instCountyNum + "</li>";
            htmString += "<li><span class='dataLabel'>Institution State:</span>" + instState + "</li>";
                     
            htmString += "</ul></body></html>";

            var winwidth = Math.max(Math.max(document.documentElement.clientWidth, window.innerWidth || 0) * .5);
            var winheight = Math.max(Math.max(document.documentElement.clientHeight, window.innerHeight || 0) * .8);
            var memoWin = $window.open('', '_showInst', "toolbar=yes,scrollbars=yes,resizable=yes,width=" + winwidth + ",height=" + winheight);
            memoWin.document.open();
            memoWin.document.write(htmString);
            memoWin.document.close();
            memoWin.setTimeout(function () { memoWin.print(); }, 1000);            
        }

        $scope.showInst = function (rssdid) {
            var url = $state.href('root.adv.institutions.summary.details', { rssd: rssdid });
            var winwidth = Math.max(Math.max(document.documentElement.clientWidth, window.innerWidth || 0) * .85);
            var winheight = Math.max(Math.max(document.documentElement.clientHeight, window.innerHeight || 0) * .85);
            $window.open(url, '_showInst', "toolbar=yes,scrollbars=yes,resizable=yes,width=" + winwidth + ",height=" + winheight);
            //$scope.$dismiss();
        }

        $scope.showBranch = function (uninum) {
            var data = { uninumber: uninum };
            AdvBranchesService.getBranchId(data).then(function (result) {
                if (result != 0) {
                    var url = $state.href('root.adv.institutions.branch.details', { branchId: result });
                    var winwidth = Math.max(Math.max(document.documentElement.clientWidth, window.innerWidth || 0) * .85);
                    var winheight = Math.max(Math.max(document.documentElement.clientHeight, window.innerHeight || 0) * .85);
                    $window.open(url, '_showBranch', "toolbar=yes,scrollbars=yes,resizable=yes,width=" + winwidth + ",height=" + winheight);
                    //$scope.$dismiss();
                }
            });
        }

        //$scope.exportDataToCsv = function () {
        //    var csvStr = "";

        //    // get header row
        //    var headerCells = $(".csvHeaderCol");
        //    var rowVals = [];
        //    for (var i = 0; i < headerCells.length; i++) {
        //        rowVals[i] = prepForCsv(headerCells[i].innerText);
        //    }
        //    csvStr = csvStr + rowVals.join(',') + '\r\n';

        //    // get data rows
        //    var dataRows = $("tr.csvDataRow");
        //    for (var i = 0; i < dataRows.length; i++)
        //    {
        //        // get row data cells
        //        var dataCells = $(dataRows[i]).find("td.csvDataCell .dataval");
        //        rowVals = [];
        //        for (var j = 0; j < dataCells.length; j++) {
        //            rowVals[j] = prepForCsv(dataCells[j].innerText);
        //        }
        //        csvStr = csvStr + rowVals.join(',') + '\r\n';
        //    }

        //    // create csv
        //    var datFile = new Blob([csvStr], { type: "text/csv" });
        //    var url = window.URL.createObjectURL(datFile);

        //    // send file
        //    var dllink = document.createElement('a');
        //    dllink.download = "closings.csv";
        //    dllink.href = url;
        //    document.body.appendChild(dllink);
        //    dllink.click();
        //    document.body.removeChild(dllink);
        //}

        function prepForCsv(val) {
            var returnVal = val.replace('"', '""');
            return '"' + returnVal + '"';
        }

        
        //function loadNonUpdatedInstsReportData() {
        //    var quarterEnd = !$scope.LQUpdateStatus ? '' : $scope.LQUpdateStatus.lqDateString;
        //    $scope.loadState = 'loading';
        //    AdminService.getOutdatedLQReport(quarterEnd).then(function (result) {
        //        $scope.loadState = 'loaded';
        //        if (result && result != null) {
        //            $scope.InstsWithoutLQUpdate = result;
        //        }
        //    });
        //}

       
        

        


        

        //function showNumRemainingDialog(lqStatusData) {
        //    Dialogger.alert(lqStatusData.numRemaining + ' institutions have NOT been updated. To view these institutions, Click the "Show Differing Items" button.');
        //}
    }
    angular
        .module('app')
        .filter('missedBrCloseFilter', function () {
            return function (dataArray, searchTerm) {
                if (!dataArray) return;
                if (searchTerm.$ == undefined) {
                    return dataArray
                } else {
                    var term = searchTerm.$.toLowerCase();
                    return dataArray.filter(function (item) {
                        return checkVal(item.fdicCert, term)
                            || checkVal(item.uninum, term)
                            || checkVal(item.address, term)
                            || checkVal(item.cityName, term)
                            || checkVal(item.countyName, term)
                            || checkVal(item.stateName, term)
                            || checkVal(item.cityinstName, term)
                            || checkVal(item.branchName, term)
                    });
                }
            }

            function checkVal(val, term) {
                if (val == null || val == undefined)
                    return false;

                return val.toLowerCase().indexOf(term) > -1;
            }
            function checkNum(val, term) {
                if (val == null || val == undefined)
                    return false;
                return val == term;
            }
        })

})();

;
(function () {
    "use strict";

    angular
        .module("app")
        .controller("NewsController", NewsController);

    NewsController.$inject = ["$scope", "AdvancedNewsService", 'Dialogger', '$uibModal'];

    function NewsController($scope, AdvancedNewsService, Dialogger, $uibModal) {

        $scope.news = [];
        $scope.channels = [];
        $scope.currentChannel = null;
        $scope.loading = false;

        $scope.openEditModal = function (news) {
            AdvancedNewsService.openModal(news);
        };


        $scope.openEditModal = function (news) {

            if (news == null) {
                news = {
                    channel: $scope.currentChannel.key
                }
            }

            $uibModal.open({
                animation: true,
                modal: true,
                backdrop: false,
                size: 'lg',
                templateUrl: 'AppJs/advanced/admin/views/editNews.html',
                controller: 'EditNewsController',
                resolve: {
                    news: function () {
                        return news;
                    }
                }
            }).result.then(function (result) {
                if (result !== 'cancel')
                    AdvancedNewsService.post(result).then(function () { $scope.refresh(); });
            });
        };

        $scope.openDeleteModal = function (news) {

            var confirmDialog = Dialogger
                .confirm("Are you sure you want to delete news - " +
                    news.title + "?");

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    AdvancedNewsService.delete(news.newsId).then(function () { $scope.refresh(); });
                }
            });

        };

        $scope.makeActive = function (news) {

            AdvancedNewsService.patch(news.newsId).then(function () { $scope.refresh(); });

        };


        $scope.refresh = function () {
            AdvancedNewsService.query('', 0, true, true).then(function (result) { $scope.news = result; });
        };

        activate();

        function activate() {
            AdvancedNewsService.getChannels().then(function (channels) {
                $scope.channels = channels;
                $scope.currentChannel = $scope.channels[0];
            });
            $scope.refresh();
        }
    }
})();;
(function () {
	'use strict';

	angular
		.module('app')
		.controller('QuarterlyDataChecksController', QuarterlyDataChecksController);

	QuarterlyDataChecksController.$inject = ["$scope","$state", "AdminService", "Dialogger", "toastr", "$uibModal", "$log"];

	function QuarterlyDataChecksController($scope, $state, AdminService, Dialogger, toastr, $uibModal, $log) {
		$scope.tabs = [
			{ heading: "LQ Values", route: "root.adv.quarterlydata.lqdata", active: true },
			{ heading: "Role Membership", route: "root.adv.quarterlydata.rolemembers", active: false },			
		];

		$scope.go = function (route) {
			$state.go(route);
		};

		activate();

		function activate() {
			
		}	
	}
})();;
(function () {
	'use strict';

	angular
		.module('app')
		.controller('RoleMemberRptController', RoleMemberRptController);

	RoleMemberRptController.$inject = ["$scope", "$state", "AdminService", "Dialogger", "toastr", "$uibModal", "$log"];

	function RoleMemberRptController($scope, $state, AdminService, Dialogger, toastr, $uibModal, $log) {
		$scope.AllRoles = [];
		$scope.RptRoleIds = [];

		
		activate();

		function activate() {
			AdminService
				.getAssignableRoles()
				.then(function (roles) {
					$scope.AllRoles = roles;
					$scope.RptRoleIds = [];
					for (var i = 0; i < $scope.AllRoles.length; i++) {
						$scope.RptRoleIds.push($scope.AllRoles[i].id);
					}
				});
		}
	}
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('UniZeroUpdateController', UniZeroUpdateController);

    UniZeroUpdateController.$inject = ["$scope", "AdminService", "AdvInstitutionsService", "Dialogger", "toastr", "$uibModal", "$log"];

    function UniZeroUpdateController($scope, AdminService, AdvInstitutionsService, Dialogger, toastr, $uibModal, $log) {
        $scope.isLoading = 0;
        $scope.uniZeroBranches = [];
        $scope.uniZeroBranchesCopy = [];
        $scope.fdicCandidatesBrs = [];
        $scope.showFdicUniSearch = false;
        $scope.toggleUninumSearch = toggleUninumSearch;
        $scope.closeUninumSearch = closeUninumSearch;
        $scope.setAsUninumVal = setAsUninumVal;
        $scope.saveUpdatedUniVals = saveUpdatedUniVals;
        $scope.checkIfIsSelectedUni = checkIfIsSelectedUni;
        $scope.clearSetUninumVal = clearSetUninumVal;
        $scope.selectedBrId = -1;
        $scope.brIdsToUpdate = [];
        $scope.uninumsToAssign = [];        
        $scope.okToContinue = true;

        var selectedRowJq = null;

        activate();

        function activate() {
            getUniZeroBranchData();
        }

        function saveUpdatedUniVals() {
            AdminService.updateBranchUninums($scope.brIdsToUpdate, $scope.uninumsToAssign).then(function (result) {
                if (result == $scope.brIdsToUpdate.length) {
                    $scope.brIdsToUpdate = [];
                    $scope.uninumsToAssign = [];
                    toastr.success(result + " changes saved.");
                }
                else {
                    toastr.error("Error updating 1 or more branches.")
                }
            });
        }

        //function saveUninumUpdates() {
        //    alert('test');
        //    var numUpdates = $scope.brIdsToUpdate.length;
        //    //Dialogger.confirm('NOTICE: You are about to update ' + numUpdates + ' branch uninumbers. <br \><br \>Do you wish to continue?', null, true).then(function () {
        //    //    AdminService.updateBranchUninums($scope.brIdsToUpdate, $scope.uninumsToAssign).then(function (result) {
        //    //        toastr.success(result + " changes saved.");
        //    //     });
        //    //});
        //}

        function clearSetUninumVal(uninumToClear) {
            var uniNumPos = $scope.uninumsToAssign.indexOf(uninumToClear);
            var brIdVal = -1;
            if (uniNumPos > -1) {
                // remove entry
                brIdVal = $scope.brIdsToUpdate[uniNumPos];
                $scope.uninumsToAssign.splice(uniNumPos, 1);
                $scope.brIdsToUpdate.splice(uniNumPos, 1);
                var brListRow = $("#brid" + brIdVal);

                //clear the css classes
                $(brListRow).removeClass("highlightSelected").removeClass("highlightUpdated");                
                $(brListRow).find("button.unifind").html("FIND");
                $(brListRow).find('.unilabel').html('0');
            }
         }

        function getUniZeroBranchData() {
            $scope.isLoading = 1;
            AdminService.getUniZeroBranches().then(function (result) {
                $scope.isLoading = 0;
                $scope.uniZeroBranches = result;
                $scope.uniZeroBranchesCopy = $scope.uniZeroBranches;
            });
        }

        function getFdicCandidates(brId) {
            $scope.isLoading = 1;
            AdvInstitutionsService.getFindFdicCandidates(brId, null, null).then(function (result) {
                $scope.fdicCandidatesBrs = result;
                $scope.isLoading = 0;
            })
        }

        function toggleUninumSearch(evt, br, brId) {
            $scope.selectedBrId = brId;
            var allTrow = $(evt.currentTarget).closest("table").find("tr");
            var btnBrIdData = $(evt.currentTarget).data("brid");
            if (btnBrIdData != brId) { return false; }

            $scope.selectedBrId = brId;
            clearAllBranchHighlights();
            var trow = $(evt.currentTarget).closest("tr");
            selectedRowJq = trow;
            trow.find("button.unifind").html("FINDING...")
            trow.addClass("highlightSelected");
            $scope.showFdicUniSearch = true;
            $scope.fdicCandidatesBrs = [];
            getFdicCandidates(brId);
        }

        function clearAllBranchHighlights() {
            $("#tblBrZeroUni tr").removeClass("highlightSelected");
            $("#tblBrZeroUni").find("button.unifind").html("FIND");
        }

        function setAsUninumVal(uninumVal, userConfirmChoice) {
            if (checkIfIsSelectedUni(uninumVal) && !userConfirmChoice) {
                $scope.okToContinue = false;
                Dialogger.confirm('WARNING! You have selected a uninumber which you have already assigned to a branch.  <br \><br \>Do you wish to continue?', null, true).then(function (confirmVal) {
                    if (confirmVal != true) {
                        $scope.okToContinue = true;
                        return false;
                    }
                    else {
                        $scope.okToContinue = true;
                        setAsUninumVal(uninumVal, true);
                    }
                });
            }

            if (!$scope.okToContinue) { return; }

            if ($scope.brIdsToUpdate.length != $scope.uninumsToAssign.length) {
                toastr.error("Unmatched branch and uninum list detected at start.");
                return;
            }

            var brIdIndex = $scope.brIdsToUpdate.indexOf($scope.selectedBrId);
            if (brIdIndex > -1) {
                $scope.brIdsToUpdate.splice(brIdIndex, 1);
                $scope.uninumsToAssign.splice(brIdIndex, 1);
            }

            if ($scope.brIdsToUpdate.length != $scope.uninumsToAssign.length) {
                toastr.error("Unmatched branch and uninum list detected at update.");
                return;
            }

            $scope.brIdsToUpdate.push($scope.selectedBrId);
            $scope.uninumsToAssign.push(uninumVal);

            $(selectedRowJq).find("span.unilabel").html(uninumVal);
            $(selectedRowJq).addClass("highlightUpdated");
        }

        function closeUninumSearch() {
            $scope.showFdicUniSearch = false;
            clearAllBranchHighlights();
        }

        function checkIfIsSelectedUni(uninum) {
            return $scope.uninumsToAssign.indexOf(uninum) >= 0 ? true : false;
        }

        function saveUninumUpdates() {

        }     
    }    
})();;
(function () {
	'use strict';

	angular
		.module('app')
		.controller('ValidateInstTypeController', ValidateInstTypeController);

	ValidateInstTypeController.$inject = ["$scope", "AdminService", "Dialogger", "toastr", "$uibModal", "$log"];

	function ValidateInstTypeController($scope, AdminService, Dialogger, toastr, $uibModal, $log) {
		$scope.isDataLoaded = false;
		$scope.isWorking = false;
		$scope.validationResults = { items: [], nicConflicts: [], nicRegConflicts: [], notFoundInNic: [] };
		$scope.unMatchedInsts = [];
		$scope.unMatchedRegInsts = [];
		$scope.notFoundInsts = [];
		$scope.StartValidationReport = StartValidationReport;
		$scope.activeTab = "entityType";
		$scope.showSection = showSection;
		
		activate();

		function activate() {
		}


		function StartValidationReport() {
			//var confirmDialog = Dialogger.confirm("WARNING: This report contains a large number of institutions. It may take several minutes to complete. Are you sure that you want to continue? <br /><br />Click OK to generate the report.");
			//confirmDialog.then(function (confirmed) {
			//	if (confirmed) {
			//		loadValidationResultData();
			//	}
			//});
			loadValidationResultData();
		}

		function loadValidationResultData() {

			$scope.isWorking = true;
			AdminService.getInstTypeValidationReport().then(function (result) {				
				if (result && result != null) {
					$scope.validationResults = result;
					$scope.unMatchedInsts = $scope.validationResults.nicConflicts;
					$scope.unMatchedRegInsts = $scope.validationResults.nicRegConflicts;
					$scope.notFoundInNic = $scope.validationResults.notFoundInNic;
					$scope.isDataLoaded = true;
				}

				$scope.isWorking = false;
			});
		}

		function showSection(sectionName) {
			$scope.activeTab = sectionName;
		}
	}
})();










;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvHelpController', AdvHelpController);

    AdvHelpController.$inject = ['$scope']; 

    function AdvHelpController($scope) {
        $scope.title = 'AdvHelpController';

        activate();

        function activate() { }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvHhiAnalysisController', AdvHhiAnalysisController);

    AdvHhiAnalysisController.$inject = ['$scope']; 

    function AdvHhiAnalysisController($scope) {
        $scope.title = 'AdvHhiAnalysisController';

        activate();

        function activate() { }
    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvAddHistoryTransactionController', AdvAddHistoryTransactionController);

    AdvAddHistoryTransactionController.$inject = ['$scope', '$state', 'HistoryService', '$log', 'toastr'];

    function AdvAddHistoryTransactionController($scope, $state, HistoryService, $log, toastr) {

        angular.extend($scope, {
			criteria: [],
            AddedSuccessfullyHistory: false,
            errorRecord: false,
            TitleMessage: "Success: Added History Record",
            hasBeenActivated : false
		});

		$scope.criteria.packetId = null;

        $scope.addhistoryHistoryCode = [{ id: "LESS_THAN_25_PERCENT", name: "Less Than 25 Percent" }, { id: "Membership", name: "Membership" }, { id: "NON_BANK_ACTIVITY", name: "Non Bank Activity" }, { id: "FIRREA", name: "FIRREA" }, { id: "International", name: "International" }, { id: "Miscellaneous", name: "Miscellaneous" }, { id: "MARKET_DEFINITION_CHANGE", name: "Market Definition Change" }];
        activate();

        function activate() {
            $scope.criteria.isPublic = false;
            $scope.hasBeenActivated = true;
        }

        $scope.getMarketNumber = function () {

            if ($scope.criteria.rSSDIDs) {

                HistoryService
                    .getMarketNumberList($scope.criteria.rSSDIDs)
                    .then(function (data) {
                        $scope.criteria.marketNumber = data;
                    });
            }
        };

        $scope.addHistory = function () {
			//if (!$scope.criteria.packetId || isNaN($scope.criteria.packetId)) {
			//	toastr.error("You must select a Firma change record packet!");
			//	return;
			//}

			var data = {
                historyCode: $scope.criteria.historyCode.id,
                transactionDate: $scope.criteria.transactionDate,
                entryDate: $scope.criteria.entryDate,
                isPublic: $scope.criteria.isPublic,
                rSSDIDs: $scope.criteria.rSSDIDs,
                copyttosubs: $scope.criteria.copyttosubs,
                marketNumber: $scope.criteria.marketNumber,
				memo: $scope.criteria.memo,
				changePacketId: $scope.criteria.packetId
            };
            HistoryService
                .postaddHistory(data.historyCode, data.transactionDate, data.entryDate, data.isPublic, data.rSSDIDs, data.copyttosubs, data.marketNumber, data.memo, data.changePacketId)
                .then(function (data) {
                    if (data.errorFlag == false) {
                        toastr.success("Success: History Record Created.");
                        //clear out items            
                        $scope.AddedSuccessfullyHistory = true;
                    }
                    else
                        toastr.error("There was an unexpected error.", data.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
                    $scope.isReadOnly = true;
                    $scope.HistorybyDataLoaded = true;
                });   
        }
        $scope.cancel = function () {
            ClearCriteria();
            $scope.AddedSuccessfullyHistory = false;

        }
        $scope.validateDate = function () {
            toastr.success("Success: History Record Created.");
        }
        function ClearCriteria() {
            $scope.criteria.historyCode.name = null;
            $scope.criteria.transactionDate = null;
            $scope.criteria.entryDate = null;
            $scope.criteria.isPublic = null;
            $scope.criteria.rSSDIDs = null;
            $scope.criteria.copyttosubs = null;
            $scope.criteria.marketNumber = null;
            $scope.criteria.memo = null;
            $scope.criteria.isPublic = false;
        }
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvDeleteHistoryInstitution', AdvDeleteHistoryInstitution);

    AdvDeleteHistoryInstitution.$inject = ['$scope', '$state', 'HistoryService', '$log', '$uibModal', 'toastr', 'Dialogger', '$sce', '$uibModalInstance'];

    function AdvDeleteHistoryInstitution($scope, $state, HistoryService, $log, $uibModal, toastr, Dialogger, $sce, $uibModalInstance) {

        angular.extend($scope, {
            confirmation: [],
            successfullyDeleted: false,
            historyId: $state.params.historyId,
            criteria:[]
        });
        $scope.criteria.deleteAllRecords = "true",
        activate();

        function activate() {
            HistoryService
               .getGetInstHistory($scope.historyId)
               .then(function (data) {
                   $scope.historyRecord = data;
               });

        }
        $scope.saveChanges = function () {
            loadDeleteConfirmation($scope.historyRecord, $scope.criteria.deleteAllRecords);
            //$uibModalInstance.close({ historyRecord: $scope.historyRecord, copyUserMemoToAll: $scope.copyUserMemoToAll, transDateType: null }); //, feedbackType: $scope.feedbackType });
            var data = {
                historyRecord: $scope.historyRecord,
                cascadeDeleteAllRelated: $scope.criteria.deleteAllRecords
            }
            HistoryService
                .postDelInstHistory(data)
                 .then(function (result) {
                     $scope.historyConfirmationDelete = true;
                     $scope.historyConfirmation = true;
                     if (result.errorFlag == false) {
                         $scope.successfullyDeleted = true;
                         toastr.success("History Memo was deleted");
                     }
                     else {
                         $scope.confirmation.erroMessageDelete = "There was an unexpected error.", data.error || "Please try again or contact support. Sorry about that.";
                     }
                 }, function (err) {
                     alert("Sorry. There was an error.");
                 });

        };
        $scope.cancel = function () {
            $uibModalInstance.close('cancel');
        };
        $scope.cancelConfirmation = function () {
            $uibModalInstance.close('done');
        };
        function loadDeleteConfirmation(data, deleteAllRecords) {
            $scope.confirmation.rssdId = data.rssdId;
            $scope.confirmation.orgHistoricName = data.orgHistoricName;
            $scope.confirmation.historyCodeDisplayName = data.historyCodeDisplayName;
            $scope.confirmation.transactionDate = data.transactionDate;
            $scope.confirmation.entryDate = data.entryDate;
            $scope.confirmation.historyIsPublic = data.historyIsPublic;
            $scope.confirmation.internalCustomMemo = data.internalCustomMemo;
            $scope.confirmation.internalAutoMemo = data.internalAutoMemo;
            $scope.confirmation.publicAutoMemo = data.publicAutoMemo;
            $scope.confirmation.deleteAllRecords = deleteAllRecords;
            $scope.confirmation.TitleMessage = "Success: History Record Deleted";
        }
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvDeleteHistoryMarket', AdvDeleteHistoryMarket);

    AdvDeleteHistoryMarket.$inject = ['$scope', '$state', 'HistoryService', '$log', '$uibModal', 'toastr', 'Dialogger', '$sce', '$uibModalInstance'];

    function AdvDeleteHistoryMarket($scope, $state, HistoryService, $log, $uibModal, toastr, Dialogger, $sce, $uibModalInstance) {

        angular.extend($scope, {
            confirmation: [],
            successfullyUpdated: false,
            criteria: [],
            historyRecord: [],
            marketNameParent: $state.params.marketName,
            historyMemoId: $state.params.historyId
        });
        
        activate();

        function activate() {
            $scope.criteria.deleteAllRecords = "true";
            HistoryService
               .getMemoMarketHistory($scope.historyMemoId)
               .then(function (data) {
                   $scope.historyRecord = data;
               });
        }
        $scope.saveChanges = function () {
            loadDeleteConfirmation($scope.historyRecord, $scope.criteria.deleteAllRecords);
            //$uibModalInstance.close({ historyRecord: $scope.historyRecord, copyUserMemoToAll: $scope.copyUserMemoToAll, transDateType: null }); //, feedbackType: $scope.feedbackType });
            var data = {
                historyRecord: $scope.historyRecord,
                cascadeDeleteAllRelated: $scope.criteria.deleteAllRecords
            }
            HistoryService
                .postMarketDelHistory(data)
                .then(function (result) {
                    $scope.historyConfirmationDelete = true;
                    $scope.historyConfirmation = true;
                    if (result.errorFlag == false) {
                        toastr.success("History Memo was deleted");
                        $scope.successfullyDeleted = true;

                    }
                    else {
                        $scope.confirmation.erroMessage = "There was an unexpected error.", data.error || "Please try again or contact support. Sorry about that.";
                    }

                }, function (err) {
                    alert("Sorry. There was an error.");
                });
        };
        $scope.cancel = function () {
            $uibModalInstance.close('cancel');
        };
        $scope.cancelConfirmation = function () {
            $uibModalInstance.close('done');
        };
        function loadDeleteConfirmation(data, deleteAllRecords) {
            $scope.confirmation.marketId = data.marketId;
            $scope.confirmation.marketNameParent = $scope.marketNameParent;
            $scope.confirmation.historyCodeDisplayName = data.historyCodeDisplayName;
            $scope.confirmation.historyTransactionDate = data.historyTransactionDate;
            $scope.confirmation.entryDate = data.entryDate;
            $scope.confirmation.historyIsPublic = data.historyIsPublic;
            $scope.confirmation.internalCustomMemo = data.internalCustomMemo;
            $scope.confirmation.internalAutoMemo = data.internalAutoMemo;
            $scope.confirmation.publicAutoMemo = data.publicAutoMemo;
            $scope.confirmation.deleteAllRecords = deleteAllRecords;
            $scope.confirmation.TitleMessage = "Success: History Record Deleted";
        }
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvEditHistoryInstitution', AdvEditHistoryInstitution);

    AdvEditHistoryInstitution.$inject = ['$scope', '$state', 'HistoryService', '$log', '$uibModal', 'toastr', 'Dialogger', '$sce', '$uibModalInstance'];

    function AdvEditHistoryInstitution($scope, $state, HistoryService, $log, $uibModal, toastr, Dialogger, $sce, $uibModalInstance) {

        angular.extend($scope, {
            confirmation: [],
            successfullyUpdated: false,
            criteria: [],
            
            historyId: $state.params.historyId
        });
       
        activate();

        function activate() {
            HistoryService
               .getGetInstHistory($scope.historyId)
               .then(function (data) {
                   $scope.historyRecord = data;
               });

        }
        $scope.saveChanges = function () {
            loadEditConfirmation($scope.historyRecord, $scope.copyUserMemoToAll);
            //$uibModalInstance.close({ historyRecord: $scope.historyRecord, copyUserMemoToAll: $scope.copyUserMemoToAll, transDateType: null }); //, feedbackType: $scope.feedbackType });
            var data = {
                historyRecord: $scope.historyRecord,
                copyUserMemoToAll: $scope.copyUserMemoToAll,
                transDateType: null
            }

            if (data.historyRecord.historyTransactionDate == undefined || data.historyRecord.historyTransactionDate == null) {
                toastr.error("Missing or invalid transaction date (format = mm/dd/yyyy)");
                $scope.successfullyUpdated = false;
                return;
            }

            HistoryService
                .postupdateInstHistory(data)
                .then(function (result) {
                    $scope.historyConfirmationEdit = true;
                    $scope.historyConfirmation = true;
                    if (result.errorFlag == false) {
                        toastr.success("History Memo was updated");
                        $scope.successfullyUpdated = true;

                    }
                    else {
                        $scope.confirmation.erroMessage = "There was an unexpected error.", data.error || "Please try again or contact support. Sorry about that.";
                    }

                }, function (err) {
                    alert("Sorry. There was an error.");
                });
        };
        $scope.cancel = function () {
           $uibModalInstance.close('cancel');
        };
        $scope.cancelConfirmation = function() {
            $uibModalInstance.close('done');
        };
        function loadEditConfirmation(data, copyUserMemoToAll) {
            $scope.confirmation.rssdId = data.rssdId;
            $scope.confirmation.orgHistoricName = data.orgHistoricName;
            $scope.confirmation.historyCodeDisplayName = data.historyCodeDisplayName;
            $scope.confirmation.transactionDate = data.historyTransactionDate;
            $scope.confirmation.entryDate = data.entryDate;
            $scope.confirmation.historyIsPublic = data.historyIsPublic;
            $scope.confirmation.internalCustomMemo = data.internalCustomMemo;
            $scope.confirmation.internalAutoMemo = data.internalAutoMemo;
            $scope.confirmation.publicAutoMemo = data.publicAutoMemo;
            $scope.confirmation.copyUserMemoToAll = copyUserMemoToAll;
            $scope.confirmation.TitleMessage = "Success: History Record Updated";
        }
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvEditHistoryMarket', AdvEditHistoryMarket);

    AdvEditHistoryMarket.$inject = ['$scope', '$state', 'HistoryService', '$log', '$uibModal', 'toastr', 'Dialogger', '$sce', '$uibModalInstance'];

    function AdvEditHistoryMarket($scope, $state, HistoryService, $log, $uibModal, toastr, Dialogger, $sce, $uibModalInstance) {

        angular.extend($scope, {
            confirmation: [],
            successfullyUpdated: false,
            criteria: [],
            historyRecord: [],
            marketNameParent: $state.params.marketName,          
            historyMemoId: $state.params.historyMemoId
        });

        activate();

        function activate() {
            HistoryService
               .getMemoMarketHistory($scope.historyMemoId)
               .then(function (data) {
                   $scope.historyRecord = data;
               });
        }
        $scope.saveChanges = function () {
            loadEditConfirmation($scope.historyRecord);
            //$uibModalInstance.close({ historyRecord: $scope.historyRecord, copyUserMemoToAll: $scope.copyUserMemoToAll, transDateType: null }); //, feedbackType: $scope.feedbackType });
            var data = {
                historyRecord: $scope.historyRecord,
                transDateType: null
            }
            HistoryService
                .postupdateMarketHistory(data)
                .then(function (result) {
                    $scope.historyConfirmationEdit = true;
                    $scope.historyConfirmation = true;
                    if (result.errorFlag == false) {
                        toastr.success("History Memo was updated");
                        $scope.successfullyUpdated = true;

                    }
                    else {
                        $scope.confirmation.erroMessage = "There was an unexpected error.", data.error || "Please try again or contact support. Sorry about that.";
                    }

                }, function (err) {
                    alert("Sorry. There was an error.");
                });
        };
        $scope.cancel = function () {
            $uibModalInstance.close('cancel');
        };
        $scope.cancelConfirmation = function () {
            $uibModalInstance.close('done');
        };
        function loadEditConfirmation(data) {
            $scope.confirmation.marketId = data.marketId;
            $scope.confirmation.marketNameParent = $scope.marketNameParent;
            $scope.confirmation.historyCodeDisplayName = data.historyCodeDisplayName;
            $scope.confirmation.historyTransactionDate = data.historyTransactionDate;
            $scope.confirmation.entryDate = data.entryDate;
            $scope.confirmation.historyIsPublic = data.historyIsPublic;
            $scope.confirmation.internalCustomMemo = data.internalCustomMemo;
            $scope.confirmation.internalAutoMemo = data.internalAutoMemo;
            $scope.confirmation.publicAutoMemo = data.publicAutoMemo;
            $scope.confirmation.TitleMessage = "Success: History Record Updated";
        }
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvHistoryInstitutionSearch', AdvHistoryInstitutionSearch);

	AdvHistoryInstitutionSearch.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'StatesService', 'HistoryService', '$log', '$uibModal', 'toastr', 'Dialogger', '$sce', '$window', '$timeout', 'AdvInstitutionsService'];

	function AdvHistoryInstitutionSearch($rootScope, $scope, $state, $stateParams, StatesService, HistoryService, $log, $uibModal, toastr, Dialogger, $sce, $window, $timeout, AdvInstitutionsService) {

        angular.extend($scope, {
            statesLoaded: false,
            HistorybyDataLoaded: true,
            HistorybyInstData: [],
            HistorybyInstDataLoaded: false,
            instPageSize:30,
            historybyInstSubmit: handleHistorybyInstSearch,
            districts: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
            district: null
        });

        var transferInCriteria = $stateParams.transferCriteria;

        activate();

        function activate() { 
            window.scrollTo(0, 0);

            // did we transfer here from a standard non-history institution search
            if (transferInCriteria)
            {
                transferFromNonHistorySearch(transferInCriteria);
            }
            
            $timeout(function () {
                $('[id="rssdId_input"]')[0].focus();

            }, 350);

            var data = {
                includeDC: true,
                includeTerritories: true
            };
            StatesService.getStateSummaries(data).then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
            $scope.criteria.rssdId = null;
            $scope.criteria.FDICCert = null;

            handleHistorybyInstSearch();
        }
        $scope.validateClearCriteria = function() {
            return $scope.criteria.name != null ||
                 $scope.criteria.county != null ||
                 $scope.criteria.city != null ||
                 $scope.criteria.state != null ||
                 $scope.criteria.rssdId != null ||
                $scope.criteria.FDICCert != null || 
                $scope.district != null;


        };

        function transferFromNonHistorySearch(transferredCriteria)
        {
            var histSearchCriteria = {
                rssdId : transferredCriteria.rssdId,
                FDICCert : transferredCriteria.FDICCert,
                name : transferredCriteria.name,
                county : transferredCriteria.county,
                state : transferredCriteria.state,
                city : transferredCriteria.city,
                zip: transferredCriteria.zip,
                district: transferredCriteria.district
            };

            $scope.criteria = histSearchCriteria;            
        }

        function handleHistorybyInstSearch() {
            var data = {
                RSSDId: $scope.criteria.rssdId ? $scope.criteria.rssdId : null,
                FDICCertNum: $scope.criteria.FDICCert ? $scope.criteria.FDICCert : null,
                OrgName: $scope.criteria.name ? $scope.criteria.name : null,
                county: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                stateId: $scope.criteria.state ? $scope.criteria.state.fipsId : null,
                cityName: $scope.criteria.city ? $scope.criteria.city.name : null,
                district: $scope.criteria.district ? $scope.criteria.district : null
            };

            if (validateCreteriaValues(data)) {

                buildCreteriaValue(data);
                $scope.HistorybyDataLoaded = false;
                $scope.HistorybyInstDataLoaded = false;
                HistoryService
                    .getHistorybyInst(data.RSSDId, data.FDICCertNum, data.OrgName, data.stateId, data.county, data.cityName, data.district)
                    .then(function (data) {
                        if (data) {
                            if (data.length == 1) {
                                $scope.clearCriteria();
                                goToInstitutionDetails(data);
                            }
                            else {
                                $scope.HistorybyInstData = data;
                                $scope.HistorybyInstDataLoaded = true;
                                $scope.HistorybyDataLoaded = true;
                            }
                        }
                    });
            }
        }
        $scope.UpdateCountysAndCitys = function () {
            $scope.criteria.city = null;
            $scope.criteria.county = null;

            var data = {
                stateFIPSId: $scope.criteria.state.fipsId
            };
            StatesService.getCityNames(data).then(function (result) {
                $scope.criteria.state.cities = result;
            });

            StatesService.getCountySummaries(data).then(function (result) {
                $scope.criteria.state.counties = result;
            });

        }
        $scope.clearCriteria = function () {
            $scope.criteria.name = null;
            $scope.criteria.county = null;
            $scope.criteria.city = null;
            $scope.criteria.state = null;
            $scope.criteria.rssdId = null;
            $scope.criteria.FDICCert = null;
            $scope.criteria.district = null;
            $scope.HistorybyInstDataLoaded = false;
            $scope.criteriaValue = [];
            $scope.HistorybyInstData = null;
            
		};

		$scope.getOrgNameFromPartial = function (partialName, numresults, historicSearch) {
			if (!numresults || isNaN(numresults)) { numresults = 10 }
			return AdvInstitutionsService.getOrgNameFromPartial(partialName, numresults, historicSearch);
		}

        function validateCreteriaValues(data)
        {
            return data.RSSDId != null ||
                   data.FDICCertNum != null ||
                   data.OrgName != null ||
                   data.county != null ||
                   data.stateId != null ||
                    data.name != null ||
                    data.district != null
                ;
        }
        function buildCreteriaValue(data) {

            $scope.criteriaValue = {
                rssid: data.RSSDId,
                name: data.OrgName,
                FDICCert: data.FDICCertNum,
                state: data.stateId ? $scope.criteria.state.name : null,
                county: data.county ? $scope.criteria.county.countyName : null,
                city: $scope.criteria.city != null ? $scope.criteria.city.name : null,
                district: $scope.criteria.district != null ? $scope.criteria.district : null
            }
        }
        function goToInstitutionDetails(result) {

            var rssdId = result[0].rssdId;
            var data = { rssdId: rssdId };


            if (result[0].isActiveOrg)
                $state.go('root.adv.institutions.summary.history', { rssd: rssdId });
            else
                $state.go('^.insthistory', data);
        }

        $scope.applyChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.sortBy = sortBy.sort.predicate;
                $scope.asc = !sortBy.sort.reverse;
            } else {
                $scope.sortBy = 'rssdId';
                $scope.asc = true;
            }

        }

        $scope.printView = function () {
            var data = [
                $scope.criteria.rssdId ? $scope.criteria.rssdId : null,
                $scope.criteria.FDICCert ? $scope.criteria.FDICCert : null,
                $scope.criteria.name ? $scope.criteria.name : null,
                $scope.criteria.county ? $scope.criteria.county.countyId : null,
                $scope.criteria.state ? $scope.criteria.state.fipsId : null,
                $scope.criteria.city ? $scope.criteria.city.name : null,
                $scope.criteria.district ? $scope.criteria.district : null,
                document.getElementById('quickSearch').value,
                $scope.sortBy,
                $scope.asc
            ];
            var reportType = 'institutionhistorysearch';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

        }
    }

    angular
     .module('app')
       .filter('instHistoryFilter', function () {
           return function (dataArray, searchTerm) {
               if (!dataArray) return;
               if (searchTerm.$ == undefined) {
                   return dataArray
               } else {
                   var term = searchTerm.$.toLowerCase();
                   return dataArray.filter(function (item) {
                       return checkVal(item.orgName, term)
                           || checkVal(item.cityName, term)
                           || checkVal(item.stateName, term)
                           || checkNum(item.rssdId, term)
                   });
               }
           }

           function checkVal(val, term) {
               if (val == null || val == undefined)
                   return false;

               return val.toLowerCase().indexOf(term) > -1;
           }
           function checkNum(val, term) {
               if (val == null || val == undefined)
                   return false;
               return val == term;
           }
       });
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvHistoryMarketSearch', AdvHistoryMarketSearch);

    AdvHistoryMarketSearch.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'HistoryService', '$log', '$uibModal', 'toastr', 'Dialogger', '$sce', '$window','AdvMarketsService','$timeout'];

    function AdvHistoryMarketSearch($scope, $rootScope, $state, StatesService, HistoryService, $log, $uibModal, toastr, Dialogger, $sce, $window, AdvMarketsService,$timeout) {
        $scope.criteria = {
            marketNumber: null,
            name: null,
            state: null,
            county: null,
            city: null,
            zip: null
        };
        angular.extend($scope, {
            statesLoaded: false,
            HistorybyMarketData: [],
            HistorybyMarketDataLoaded: false,
            HistorybyDataLoaded: true,
            historybyMarketSubmit: handleHistorybyMarketSearch,
            instPageSize: 30
        });
        activate();

        


        function activate() {
            window.scrollTo(0, 0);        

            var data = {
                includeDC: true,
                includeTerritories: true
            };
            StatesService.getStateSummaries(data).then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
            handleHistorybyMarketSearch();

            //  window.document.getElementById("name").focus();
            $timeout(function () { $('#name')[0].focus(); }, 350);            
        }


        $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;

            if (key == 13)
                return true;

            key = String.fromCharCode(key);
            var regex = /^[0-9]$/;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();

            }
        };


        $scope.UpdateCountysAndCitys = function () {
            $scope.criteria.city = null;
            $scope.criteria.county = null;

            var data = {
                stateFIPSId: $scope.criteria.state.fipsId
            };
            StatesService.getCityNames(data).then(function (result) {
                $scope.criteria.state.cities = result;
            });

            StatesService.getCountySummaries(data).then(function (result) {
                $scope.criteria.state.counties = result;
            });
            
        }
        $scope.validateClearCriteria = function () {
            return $scope.criteria.number != null ||
                 $scope.criteria.name != null ||
                 $scope.criteria.city != null ||
                 $scope.criteria.state != null ||
                 $scope.criteria.county != null ||
                 $scope.criteria.zip != null;

        };
        $scope.clearCriteria = function () {
            $scope.criteria.number = null;
            $scope.criteria.name = null;
            $scope.criteria.city = null;
            $scope.criteria.state = null;
            $scope.criteria.county = null;
            $scope.criteria.zip = null;
            $scope.criteriaValue = [];
            $scope.HistorybyMarket = null;
            $scope.HistorybyMarketDataLoaded = false;

        };
        function handleHistorybyMarketSearch() {
            var data = {
                marketNumber: $scope.criteria.number,
                marketName: $scope.criteria.name,
                stateId: $scope.criteria.state ? $scope.criteria.state.fipsId : null,
                countyId: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                cityName: $scope.criteria.city ? $scope.criteria.city.name : null,
                zip: $scope.criteria.zip
            };
            if (validateCreteriaValues(data)) {
                buildCreteriaValue(data);
                $scope.HistorybyDataLoaded = false;
                $scope.HistorybyMarketDataLoaded = false;
                AdvMarketsService
                    .getMarketsSearchData(data)
                    .then(function (data) {
                        $scope.HistorybyMarket = groupByResults(data);
                        if ($scope.HistorybyMarket.length == 1) {
                            goToMarketDetails(data);
                        }
                        else {
                        $scope.HistorybyMarketDataLoaded = true;
                        $scope.HistorybyDataLoaded = true;
                        }
                    });
            }
        }
        function validateCreteriaValues(data) {
            return data.marketNumber != null ||
                   data.marketName != null ||
                   data.stateId != null ||
                   data.countyId != null ||
                   data.cityName != null ||
                   data.zip != null;
        }
        function groupByResults(data) {
            var newData = [];
            for (var i = 0; i < data.length; i++) {
                var rec = data[i];
                var market = _.find(newData, { marketId: rec.marketId });


                if (typeof market == "undefined") {//already added market to data variable?
                    newData.push(rec);
                } 
            }
            return newData;
        }
        function buildCreteriaValue(data) {

            $scope.criteriaValue = {
                marketNumber: data.marketNumber,
                marketName: data.marketName,
                FDICCert: data.FDICCertNum,
                state: data.stateId ? $scope.criteria.state.name : null,
                county: data.countyId ? $scope.criteria.county.countyName : null,
                city: $scope.criteria.city != null ? $scope.criteria.city.name : null,
                zip: data.zip

            }
        }
        function goToMarketDetails(result) {

            var marketId = result[0].marketId;

            $state.go('root.adv.markets.detail.history', { market: marketId });
  
        }

        // This is for the Sentinal directive to capture sort column
        $scope.applyChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.sortBy = sortBy.sort.predicate;
                $scope.asc = !sortBy.sort.reverse;
            } else {
                $scope.sortBy = 'marketName';
                $scope.asc = true;
            }

        }
        function goToMarketDetails(result) {

            var marketId = result[0].marketId;

            $state.go('root.adv.markets.detail.history', { market: marketId });
  
        }
        $scope.printView = function () {
            var data = [
                $scope.criteria.number,
                $scope.criteria.state ? $scope.criteria.state.fipsId : null,
                $scope.criteria.county ? $scope.criteria.county.countyId : null,
                $scope.criteria.city ? $scope.criteria.city.name : null,
                $scope.criteria.zip,
                $scope.criteria.name,
                document.getElementById('quickSearch').value,
                $scope.sortBy,
                $scope.asc
            ];
            var reportType = 'markethistorysearch';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

        }
    }

        angular
     .module('app')
       .filter('instHistoryMarketFilter', function () {
           return function (dataArray, searchTerm) {
               if (!dataArray) return;
               if (searchTerm.$ == undefined) {
                   return dataArray
               } else {
                   var term = searchTerm.$.toLowerCase();
                   return dataArray.filter(function (item) {
                       return checkVal(item.marketId.toString(), term)
                           || checkVal(item.marketName, term)
                   });
               }
           }

           function checkVal(val, term) {
               if (val == null || val == undefined)
                   return false;

               return val.toLowerCase().indexOf(term) > -1;
           }
           function checkNum(val, term) {
               if (val == null || val == undefined)
                   return false;
               return val == term;
           }
       });

})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsHistoryController', AdvInstitutionsHistoryController);

    AdvInstitutionsHistoryController.$inject = ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$templateCache', '$uibModal', 'AdvInstitutionsService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants', 'toastr', '$log', '$window','$sce','HistoryService'];

    function AdvInstitutionsHistoryController($scope, $rootScope, $state, $stateParams, $timeout, $templateCache, $uibModal, AdvInstitutionsService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants, toastr, $log, $window, $sce, HistoryService) {
        angular.extend($scope, {
            historyReady: false,
            filter: "all",
            showPublic: false,
            includeBranchTxns: true,
            institutionHistory: null,
            hasAdjusted: false,
            expand: true,
            branchTxnTypes: ["Openings", "Closings", "Sales", "Location Changes"],
            hasBranchTxnTypeFilter: function () {
                return _.indexOf(this.branchTxnTypes, this.filter) > -1;
            },
            years: [],
            hasYearFilter: function () {
                return _.indexOf(this.years, this.filter) > -1;
            },
            checkNoResults: function () {
                return $scope.institution != null ? _.filter(_.flatMap($scope.institution.history, function (e) { return e.data; }),
                        function (e) { return $scope.historyFilter(e) }).length == 0 : false;
            },
            setYearFilter: function (year) {
                $scope.filter = year;
                var yearChunk = _.find($scope.institution.history, { year: year });
                if (yearChunk)
                    yearChunk.isOpen = true;
            },
            showBranchTransactions: false,
            clearBranchTxnTypeFilter: function (showbranch) {
                $scope.showBranchTransactions = showbranch;
                if (!this.showBranchTransactions && this.hasBranchTxnTypeFilter()) {
                    this.filter = "all";
                }
            },
            historyFilter: function (hist) {
                if (!$scope.showBranchTransactions && (hist.isBranchOpening || hist.isBranchClosing || hist.isBranchSale || hist.isBranchRelocation)) {
                    return false;
                }
                if ($scope.filter == 'all')
                    return true;
                if ($scope.filter == 'mergers')
                    return hist.isMerger;
                if ($scope.filter == 'acquisitions')
                    return hist.isAcquisition;
                if ($scope.filter == 'Openings')
                    return hist.isBranchOpening;
                if ($scope.filter == 'allbranchtrans')
                    return hist.isBranch;
                if ($scope.filter == 'Closings')
                    return hist.isBranchClosing;
                if ($scope.filter == 'Sales')
                    return hist.isBranchSale;
                if ($scope.filter == 'Location Changes')
                    return hist.isBranchRelocation;
                if ($scope.filter == 'failures')
                    return hist.isFailure;
                if ($scope.filter == 'misc')
                    return hist.isMisc;
                return true;
            },
            closeOpenAllYearGroups: function (open) {
                $scope.expand = open;
                angular.forEach($scope.institution.history, function (obj, index) {
                    obj.isOpen = open === true ? true : open === false ? false : !obj.isOpen;
                });
            },
            loadHistory: function (isPublic) {

                $scope.showPublic = isPublic;
                angular.forEach($scope.institutionHistory, function (val, key) {
                    var year = val.year;
                    if (_.indexOf($scope.years, year) == -1)
                        $scope.years.push(year);
                });

                $scope.years.sort().reverse();

                var historyByYear = [];

                if (!isPublic) {

                    for (var i = 0; i < $scope.years.length; i++) {
                        var year = $scope.years[i];
                        var chunk = _.filter($scope.institutionHistory, { year: year });

                        historyByYear.push({ year: year, data: chunk });
                    }

                }
                else {

                    for (var i = 0; i < $scope.years.length; i++) {
                        var year = $scope.years[i];
                        var chunk = _.filter($scope.institutionHistory, { year: year });
                        var publicChunck = [];

                        for (var x = 0; x < chunk.length; x++) {
                            if (chunk[x].publicMemoText != "") {
                                publicChunck.push(chunk[x]);
                            }
                        }
                        historyByYear.push({ year: year, data: publicChunck });
                    }
                }
                //console.log(historyByYear);
                $scope.institution.history = historyByYear;

                $scope.historyReady = true;
                //set the 
                //set everything to be open
                angular.forEach($scope.institution.history, function (obj, index) {
                    obj.isOpen = true;
                });

                //ok so got it to work, but really I have to call this method twice.  I dont like this but need it done.
                $scope.clearBranchTxnTypeFilter(true);
                $scope.clearBranchTxnTypeFilter(true);
            }
        });


        var getDetail = true;
        var getBranches = false;
        var getOperatingMarkets = false;
        var getHistory = false;
        $scope.sortBy = 'city';
        $scope.asc = true;

        $scope.showPublic = false;
        $scope.successfullyUpdated = false;
        $scope.historyConfirmation = false;
        $scope.historyConfirmationEdit = false;
        $scope.historyConfirmationDelete = false;
        $scope.successfullyDeleted = false;
        $scope.instData = [];
        $scope.hasInst = false;
        $scope.institutionLoaded = true;
        $scope.confirmation = [];
		$scope.Inactive = false;
        $scope.histRSSDID = $state.params.rssdId;

        $scope.go = function (route) {
            var data = {
                rssd: $state.params.rssd
            };
            $state.go(route, data);
        };
        $scope.active = function (route) {
            return $state.is(route);
        };

        activate();

        function activate() {

            window.scrollTo(0, 0);
            $scope.institutionLoaded = false;
            $scope.historyReady = false;
            $rootScope.isInWizard = false;            
                    loadInactiveHistory();
                    $scope.institutionLoaded = true;
                    getAdjusted();
               
        }
            function loadDefintition(result) {
                    $scope.instData = result.definition;
                    $scope.mostRecentTransDateString = '';
                    $scope.totalInstItems = $scope.instData.orgs.length;
                    $scope.hasInst = true;
                    $scope.rssd = $state.params.rssd;
                    $scope.instItemsPerPage = 30;
                    $scope.currentInstPage = 1;
                    $scope.instPageCount = function () {
                        return Math.ceil($scope.instData.orgs.length / $scope.instItemsPerPage);
                    };
                    $scope.totalInstItems = $scope.instData.orgs.length;
                    $scope.instDataPages = _.chunk($scope.instData.orgs, $scope.instItemsPerPage);
                    $scope.instDataReady = true;


                    $scope.header = "";
                    if ($scope.instData.orgType == "Tophold") {
                        $scope.header = "Tophold";
                    }
                    else if ($scope.instData.class == "BANK" && $scope.instData.branchCount > 0) {
                        $scope.header = "Bank Parent";
                    }
                    else if ($scope.instData.class == "BANK" && $scope.instData.branchCount == 0) {
                        $scope.header = "Bank";
                    }
                    else if ($scope.instData.class == "THRIFT" && $scope.instData.branchCount > 0) {
                        $scope.header = "Thrift Parent";
                    }
                    else if ($scope.instData.class == "THRIFT" && $scope.instData.branchCount > 0) {
                        $scope.header = "Thrift";
                    }
                    buildDetailsLink($scope.institutionHistory);
                    $scope.loadHistory(false);
    
            }
            function getAdjusted() {
                HistoryService
                   .hasAdjustedReport($state.params.rssdId)
                   .then(function (data) {
                       $scope.hasAdjusted = data;
  
                   });
            }
            function loadInactiveHistory() {
                AdvInstitutionsService.getInstitutionHistoryData({ rssdId: $state.params.rssdId }).then(function (result) {
                    if (result && result.definition != null) {
                        if ($scope.institution)
                            $scope.institution.history = result.history;
                        else
                            $scope.institution = result;
                        
                        $scope.institutionHistory = result.history;
                        loadDefintition(result);
                        $scope.Inactive = true;
                        $scope.mostRecentTransDateString = result.mostRecentTransDateString;
                    }
                    else
                    {
                        $scope.historyReady = true;
                    }
                });

            }
            function buildDetailsLink(result) {
                var memoArray = [];
                var linkTitle;
                for (var i = 0; i < result.length; i++) {
                    result[i].memo = $sce.trustAsHtml(result[i].memo);
                    result[i].publicMemoText = $sce.trustAsHtml(result[i].publicMemoText);

                }
			}

		
            $scope.cancelConfirmation = function() {
                $scope.successfullyUpdated = false;
                $scope.historyConfirmationEdit = false;
                $scope.historyConfirmation = false;
                activate();
            }
            $scope.cancelDelete = function () {
                $scope.successfullyUpdated = false;
                $scope.historyConfirmationDelete = false;
                $scope.historyConfirmation = false;
                activate();
            }
            $scope.printDiv = function (divName) {
                var printContents = document.getElementById(divName).innerHTML;
                var popupWin = window.open('', '_blank', 'width=800,height=800');
                popupWin.document.open();
                popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' +printContents + '</body></html>');
                popupWin.document.close();
            }

            $scope.openGetHistoryForm = function (historyId) {
                $state.params.historyId = historyId;
                $uibModal.open({
                    animation: true,
                    modal: true,
                    backdrop: false,
                    size: 'lg',
                    templateUrl: 'AppJs/advanced/history/views/editInstHistoryTransaction.html',
                    controller: 'AdvEditHistoryInstitution'
                }).result.then(function (result) {
                    if(result == "done")
                        activate();
                });
            };
            $scope.openGetDelHistoryForm = function (historyId) {
                $state.params.historyId = historyId;
                $uibModal.open({
                    animation: true,
                    modal: true,
                    backdrop: false,
                    size: 'lg',
                    templateUrl: 'AppJs/advanced/history/views/delInstHistoryTransaction.html',
                    controller: 'AdvDeleteHistoryInstitution'
                }).result.then(function (result) {
                    if (result == "done")
                        activate();
                });
            };

            $scope.printView = function (data, reportType) {
                data.push($scope.sortBy);
                data.push($scope.asc);
                data.push($scope.showPublic);
                data.push($scope.filter);
                var jData = angular.toJson(data);
                $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData,'_blank');
            };

            $scope.showChangeRecDoc = function (docUrl) {
                if (!docUrl || docUrl == "") {
                    return false;
                }
                var winWidth = window.innerWidth * 0.75;
                var winHeight = window.innerHeight * 0.8;
                var recordDocWin = window.open(docUrl, 'recordDocWin', 'location=yes,height=' + winHeight + ',width=' + winWidth + ',scrollbars=yes,status=yes');
                return false;
            }

        }    

})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketHistoryController', AdvMarketHistoryController);

    AdvMarketHistoryController.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'AdvMarketsService', 'uiGridConstants', 'leafletBoundsHelpers', 'StatesService', '$window','$sce'];

    function AdvMarketHistoryController($rootScope, $scope, $state, $stateParams, AdvMarketsService, uiGridConstants, leafletBoundsHelpers, StatesService, $window, $sce) {
        angular.extend($scope, {
            historyReady: false,
            marketName: "",
            filter: "all",
            includeBranchTxns: true,
            showPublic: false,

            checkNoResults: function () {
                return $scope.market != null ? _.filter(_.flatMap($scope.market.history, function (e) { return e.data }),
                        function (e) { return $scope.historyFilter(e) }).length == 0 : false;
            },
            branchTxnTypes: ["Openings", "Closings", "Sales", "Location Changes"],
            hasBranchTxnTypeFilter: function () {
                return _.indexOf(this.branchTxnTypes, this.filter) > -1
            },
            years: [],
            hasYearFilter: function () {
                return _.indexOf(this.years, this.filter) > -1;
            },
            setYearFilter: function (year) {
                $scope.filter = year;
                var yearChunk = _.find($scope.market.history, { year: year });
                if (yearChunk) {
                    console.log(yearChunk);
                    yearChunk.isOpen = true;
                }

            },
            showBranchTransactions: true,
            clearBranchTxnTypeFilter: function (showbranch) {
                $scope.showBranchTransactions = showbranch;
                if (!this.showBranchTransactions && this.hasBranchTxnTypeFilter()) {
                    this.filter = "all";
                }
            },
            historyFilter: function (hist) {
                if (!$scope.showBranchTransactions && (hist.isBranchOpening || hist.isBranchClosing || hist.isBranchSale || hist.isBranchRelocation)) {
                    return false;
                }
                if ($scope.filter == 'all')
                    return true;
                if ($scope.filter == 'TopholdParent')
                    return hist.isTopholdAndInstitution;
                if ($scope.filter == 'Openings')
                    return hist.isBranchOpening;
                if ($scope.filter == 'Closings')
                    return hist.isBranchClosing;
                if ($scope.filter == 'allbranchtrans')
                    return hist.isBranch;
                if ($scope.filter == 'Sales')
                    return hist.isBranchSale;
                if ($scope.filter == 'Location Changes')
                    return hist.isBranchRelocation;
                if ($scope.filter == 'failures')
                    return hist.isFailure;
                if ($scope.filter == 'MarketDefintion')
                    return hist.isMarketDefinitionChange;
                return true;
            },
            closeOpenAllYearGroups: function (open) {
                angular.forEach($scope.market.history, function (obj, index) {
                    obj.isOpen = open === true ? true : open === false ? false : !obj.isOpen;
                });
            }

        });
        $scope.go = function (route) {
            $state.go(route);
        };
        $scope.active = function (route) {
            return $state.is(route);
        };

        $scope.$parent.hideEditDiv = false;
        //$scope.$parent.$parent.marketName = null;
        $scope.market = null;
        $scope.listOfCities = [];
        $scope.listOfCounties = [];

        activate();


        function activate() {            
            loadHistory();
            //$scope.marketLoaded = false;

            //AdvMarketsService.getMarketByIdAdv({ marketId: $stateParams.market, getDefinition: true })
            //    .then(function (result) {
            //        // $scope.$parent.$parent.marketName = result.definition.name;

            //        if ($scope.market)
            //            $scope.market.definition = results.definition;
            //        else
            //            $scope.market = result;
            //        //loadCountyView($scope.market);
            //        $scope.marketLoaded = true;
            //    });
        }

        function loadHistory() {
            AdvMarketsService.getMarketHistoryById({ marketId: $stateParams.market, getHistory: true }).then(function (result) {
                //if (result != null) {
                //    $scope.market.history = result.history;
                //    $scope.market.definition = result.definition;
                //}
                if ($scope.market)
                    $scope.market.history = result.history;
                else
                    $scope.market = result;

                buildDetailsLink(result);

                $scope.marketName = result.definition.name;
                $scope.$parent.hideEditDiv = false;

                angular.forEach(result.history, function (val, key) {
                    var year = val.year;
                    if (_.indexOf($scope.years, year) == -1)
                        $scope.years.push(year);
                });

                $scope.years.sort().reverse();

                var historyByYear = [];
                for (var i = 0; i < $scope.years.length; i++) {
                    var year = $scope.years[i];
                    var chunk = _.filter(result.history, { year: year });

                    historyByYear.push({ year: year, data: chunk, isOpen: true });
                }
                console.log(historyByYear);
                $scope.market.history = historyByYear;

                $scope.historyReady = true;

            });
        }
        function buildDetailsLink(result) {
            var memoArray = [];
            var linkTitle;
            for (var i = 0; i < result.history.length; i++) {
                result.history[i].memo = $sce.trustAsHtml(result.history[i].memo);
                var value = result.history[i].memo;
            }
        }
        $scope.printView = function (data, reportType) {

            var jData = angular.toJson(data);
            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }

    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvStructureAdjustedHistoryReportController', AdvStructureAdjustedHistoryReportController);

    AdvStructureAdjustedHistoryReportController.$inject = ['$scope', '$state', 'HistoryService','$window'];

    function AdvStructureAdjustedHistoryReportController($scope, $state, HistoryService, $window) {

        angular.extend($scope, {
            reportLoaded: false,
            instData: [],
            branches: [],
            rssd: $state.params.rssd,
            title: 'Structure History Report - Inactive ',
            labelFailure: null,
            institutions:[]
        });
        $scope.todaysDate = new Date();
        activate();

        function activate() {
            HistoryService
               .getStructureAdjustedReport($scope.rssd)
               .then(function (data) {
                   if (data) {
                       $scope.instData = data;
                       $scope.branches = data.branches;
                       $scope.institutions = data.institutions;
                       if ($scope.instData.hasAdjustedDeposits ||
                           $scope.instData.hasAdjustedAssets) {
                           $scope.title = "Structure & Adjusted History Report - Inactive " + data.orgType.toLowerCase() == 'tophold' ? 'Tophold' : 'Institution';
                       }
                       else
                       {
                           $scope.title = "Structure History Report - Inactive " + (data.orgType.toLowerCase() == 'tophold' ? 'Tophold' : 'Institution');
                       }
                       if (data.mostRecentTransDateString)
                       {
                           $scope.title = $scope.title + ' (as of ' + data.mostRecentTransDateString + ')';
                       }
                       $scope.reportLoaded = true;
                   }
               });
        }
        $scope.printView = function (data, reportType) {

            var jData = angular.toJson(data);
            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }

    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('HistoryController', HistoryController);

    
    HistoryController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'HistoryService', '$log','$uibModal', 'toastr' , 'Dialogger', '$sce', '$window', '$filter', '$timeout'];

    function HistoryController($scope, $rootScope, $state, StatesService, HistoryService, $log, $uibModal,toastr, Dialogger, $sce, $window, $filter, $timeout) {
        $scope.criteria = {
            marketNumber: null,
            state: null,
            county: null,
            city: null,
            zip: null
        };
        angular.extend($scope, {
            //isIndex: isOnIndexPage($state.current),
            //subTitle: getSubTitle($state.current),
        states: [],
        statesLoaded: false,
        HistorybyMarketData: [],
        HistorybyMarketDataLoaded: false,
        HistorybyDataLoaded: true,        
        //historybyMarketSubmit: handleHistorybyMarketSearch,
        HistorybyInstData: [],
        HistorybyInstDataLoaded: false,
        //historybyInstSubmit: handleHistorybyInstSearch,
        HistorybyDateData: [],
        HistorybyDateDataLoaded: false,
        historybyDateSubmit: handleHistorybyDateSearch,
        historyAddTransResult: "",
        isReadOnly: false,
        searchby: 'byEntryDate',
        editHistory: handleEditHistory,
        });
        
        $scope.availableHistCodes = [];
        $scope.selectedHistCodes = [];
        $scope.searchingHistCodes = [];
        $scope.dateSearchItemCount = null;
        $scope.doDateOnlySearch = true;
        $scope.unfilteredHistoryIds = [];

        activate();

        $scope.criteriaValue = [];
        $scope.searchby = "";
        $scope.criteria.entryDate = new Date;
        $scope.hiddeCriteria = false;
        $scope.hideResults = true;
        $scope.stateFilter = [];
        $scope.stateFilterId = null;
        $scope.brStartSpecId = null;
        $scope.districtFilterId = 0;
        $scope.stateFilter = null;
        $scope.districtIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        $scope.districtStates = [[], [33, 44, 50], [9, 34, 36, 72, 78], [10, 34, 42], [21, 39, 42, 54], [11, 24, 37, 45, 51, 54], [1, 12, 13, 22, 28, 47], [17, 18, 19, 26, 55], [5, 17, 18, 21, 28, 29, 47], [26, 27, 30, 38, 46, 55], [8, 20, 29, 31, 35, 40, 56], [22, 35, 48], [2, 4, 6, 15, 16, 32, 41, 49, 53, 60, 64, 66, 68, 69, 70, 74]]
        $scope.numBranchHistCodes = 0;


        //Top Category options ===================================================
        //$scope.topCategoryItems = ["Acquisitions", "Miscellaneous"];
        $scope.topCategoryItems = [
                                        { id: "Acquisitions", text: "Acquisitions" },
                                        { id: "TopHoldMisc", text: 'Miscellaneous' }
        ];
        $scope.topCategoryselected = [];

        $scope.brStartSpecFilterChanged = function (filterVal) {
            $scope.brStartSpecId = filterVal
        }

        $scope.clearFilters = function () {
            $scope.stateFilterId = null;
            $scope.districtFilterId = 0;
            $scope.brStartSpecId = null;
            $scope.stateFilterChanged($scope.stateFilterId);
            $scope.districtFilterChanged($scope.districtFilterId);
            $scope.brStartSpecFilterChanged($scope.brStartSpecId )
        }

        $scope.stateFilterChanged = function (selectedValue) {
            $scope.stateFilterId = selectedValue;
            $scope.resetDistrictDd();
            if (selectedValue != "") {
                //$scope.filterDistrictsToState(selectedValue);
            }
        }

        $scope.districtFilterChanged = function (selectedValue) {
            $scope.districtFilterId = selectedValue;
            $scope.resetStateDd();
            if (selectedValue != "") {
                //$scope.filterStatesToDistrict(selectedValue);
            }
        }

        $scope.getDistrictIdsByState = function (stateFipsId) {
            var districtIds = [];
            for (var i = 1; i <= 12; i++) {
                if ($scope.districtStates[i].includes(parseInt(stateFipsId))) {
                    districtIds.push(i);
                }
            }

            return districtIds;
        }

        $scope.filterStatesToDistrict = function (districtId) {
            $("#stateFilter").children("option").hide();
            $("#stateFilter option")[0].show();
            var stateIdsToShow = $scope.districtStates[districtId];
            for (var i = 0; i < stateIdsToShow.length; i++) {
                //$("#stateFilter option[value=" + stateIdsToShow[i] + "]").show();
            }            
        }

        $scope.filterDistrictsToState = function (stateFipsId) {
            var districtIdsToShow = $scope.getDistrictIdsByState(stateFipsId);
            $("#distictFilter").children("option").hide();
            $("#distictFilter option")[0].show();
            for (var i = 0; i < districtIdsToShow.length; i++) {
                $("#distictFilter option[value=" + districtIdsToShow[i] + "]").show();
            }
        }

        $scope.resetStateDd = function () {
            $("#stateFilter").children("option").show();
        }

        $scope.resetDistrictDd = function () {
            $("#distictFilter").children("option").show();
        }

        $scope.toggle = function (item, list) {
            var idx = list.indexOf(item.id);
            if (idx > -1) {
                list.splice(idx, 1);
            }
            else {
                list.push(item.id);
            }
        };
        $scope.displayCriteria = function (value) {
            $scope.hiddeCriteria = !value;

        };
        $scope.toggletopCategory = function (item, list) {
            var idx = list.indexOf(item.id);
            if (idx > -1) {
                list.splice(idx, 1);
            }
            else {
                list.push(item.id);
            }
        };

        $scope.topCategoryexists = function (item, list) {
            return list.indexOf(item.id) > -1;
        };

        $scope.isIndeterminate = function () {
            return ($scope.selected.length !== 0 &&
                $scope.topCategoryselected.length !== $scope.topCategoryItems.length);
        };

        $scope.isChecked = function () {
            return $scope.topCategoryselected.length === $scope.topCategoryItems.length;
        };

        $scope.toggleAll = function () {
            if ($scope.topCategoryselected.length === $scope.topCategoryItems.length) {
                $scope.topCategoryselected = [];
            } else if ($scope.topCategoryselected.length === 0 || $scope.topCategoryselected.length > 0) {
                $scope.topCategoryselected = ["Acquisitions", "TopHoldMisc"];
            }
        };


        $scope.toggleHistCode = function (histCode) {
            // if it is not in the selected array, move it there. If it is in the array, remove it
            var histCodeId = histCode.historyCodeId;
            var posInSelectedList = $scope.selectedHistCodes.indexOf(histCodeId);
            if (posInSelectedList == -1) // this is a code that is just now being selected, add it to the list
            {
                $scope.selectedHistCodes.push(histCodeId);
                $scope.searchingHistCodes.push(histCode);
                if (histCode.primaryOrgTypeId == 3) {
                    $scope.numBranchHistCodes++; 
                }

            }
            else // this was a code that was previously selected, and is now being deselected/removed
            {
                $scope.selectedHistCodes.splice(posInSelectedList, 1);
                $scope.searchingHistCodes.splice(posInSelectedList, 1);
                if (histCode.primaryOrgTypeId == 3) {
                    $scope.numBranchHistCodes--;
                }
            }

            $scope.doDateOnlySearch = ($scope.selectedHistCodes.length == 0)
            $scope.getHistoryByDateCounts();
        }

        $scope.getHistoryByDateCounts = function () {
            if ($scope.criteria.startDate == null || $scope.criteria.endDate == null) {
                if ($scope.selectedHistCodes.length > 0) {
                    toastr.error("Start Date and End Date are required!");
                }
                return;
            }

            $scope.HistorybyDataLoaded = false;
            $scope.SearchCriteriaChanged = true;

            var isEntryDate;
            if ($scope.criteria.searchby == 'byEffectiveDate')
            {
                isEntryDate = false;
            }
            else 
            {
                isEntryDate = true
            }
            

            var searchData = {
                startDate: $scope.criteria.startDate,
                endDate: $scope.criteria.endDate,
                isEntryDate: isEntryDate,
                historyCodeIds: ($scope.doDateOnlySearch ? [] : $scope.selectedHistCodes)
            };

            $scope.hideResults = true;

            HistoryService.getHistoryByDateCounts(searchData.startDate, searchData.endDate, searchData.isEntryDate, searchData.historyCodeIds).then(function (data) {
                $scope.dateSearchItemCount = data;
                $scope.HistorybyDataLoaded = true;                
            });
        }

        //Top Category options ===================================================



        //Parent Category options ===================================================
       // $scope.parentCategoriesItems = ["Mergers", "Acquisitions", "Branch Transactions", "Failures", "Miscellaneous", "Pre-CASSIDI Footnote"];
        $scope.parentCategoriesItems = [
                                        { id: "Mergers", text: "Mergers" },
                                        { id: "Acquisitions", text: 'Acquisitions' },
                                         { id: "AllBranches", text: 'Branch Transactions' },
                                          { id: "Failure", text: 'Failures' },
                                           { id: "Misc", text: 'Miscellaneous' },
                                            { id: "PreCassidi", text: 'Pre-CASSIDI Footnote' }
                                         ];


        $scope.parentCategoriesselected = [];
        $scope.toggleparentCategories = function (item, list) {
            var idx = list.indexOf(item.id);
            if (idx > -1) {
                list.splice(idx, 1);
                if (item.id == 'AllBranches')
                {
                    $scope.toggleAllbranchCategories();
                }
            }
            else {
                if (item.id == 'AllBranches')
                {
                    $scope.toggleAllbranchCategories();
                }
                list.push(item.id);
            }
        };

        $scope.existsparentCategories = function (item, list) {
            return list.indexOf(item.id) > -1;
        };

        $scope.isIndeterminateparentCategories = function () {
            return ($scope.parentCategoriesselected.length !== 0 &&
                $scope.parentCategoriesselected.length !== $scope.parentCategoriesItems.length);
        };

        $scope.isCheckedparentCategories = function () {
            return $scope.parentCategoriesselected.length === $scope.parentCategoriesItems.length;
        };

        $scope.toggleAllparentCategories = function () {
            if ($scope.parentCategoriesselected.length === $scope.parentCategoriesItems.length) {
                $scope.parentCategoriesselected = [];
                $scope.toggleAllbranchCategories();
            } else if ($scope.parentCategoriesselected.length === 0 || $scope.parentCategoriesselected.length > 0) {
                $scope.parentCategoriesselected = ["Mergers", "Acquisitions", "AllBranches", "Failure", "Misc", "PreCassidi"];
                $scope.toggleAllbranchCategories();

            }
        };

        $scope.setStateFilterVal = function (stateFilterDd) {
            var stateVal = $(stateFilterDd).val();
            $scope.stateFilterId = stateVal;
            //$('#stateFilter').val($scope.stateFilterId);
        }

        $scope.setDistrictFilterVal = function (districtId) {
            $scope.districtFilterId = districtId == "" || isNaN(districtId) ? null : districtId;
        }

        $scope.setFilterDdDisplay = function () {
            if (!$scope.stateFilterId || !$scope.stateFilterId.length || $scope.stateFilterId.length < 1 || $scope.stateFilterId.length > 2) {
                $scope.stateFilterId = "";
            }
            $('#stateFilter').val($scope.stateFilterId);

            if (!$scope.districtFilterId || $scope.districtFilterId < 1) {
                $scope.districtFilterId = "";
            }

            $('#distictFilter').val($scope.districtFilterId);
        }

        //Parent Category options ===================================================

        //Branch Category options ===================================================
        $scope.branchCategoriesItems = [
                                        { id: "BranchOpening", text: "Openings" },
                                        { id: "BranchClosing", text: 'Closings' },
                                        { id: "BranchSale", text: 'Sales' },
                                        { id: "BranchLocationChange", text: 'Location Changes' }
                                        ];


        $scope.branchCategoriesselected = [];
        $scope.togglebranchCategories = function (item, list) {
            var idx = list.indexOf(item.id);
            if (idx > -1) {
                list.splice(idx, 1);
            }
            else {
                list.push(item.id);
            }
        };

        $scope.branchCategoriesexists = function (item, list) {
            return list.indexOf(item.id) > -1;
        };

        $scope.isIndeterminatebranchCategories = function () {
            return ($scope.branchCategoriesselected.length !== 0 &&
                $scope.branchCategoriesselected.length !== $scope.branchCategoriesItems.length);
        };

        $scope.isCheckedbranchCategories = function () {
            return $scope.branchCategoriesselected.length === $scope.branchCategoriesItems.length;
        };

        $scope.toggleAllbranchCategories = function () {
            if ($scope.branchCategoriesselected.length === $scope.branchCategoriesItems.length) {
                $scope.branchCategoriesselected = [];
                //check to see if we 
                var idx = $scope.parentCategoriesselected.indexOf("AllBranches");
                if (idx > -1) {
                    $scope.parentCategoriesselected.splice(idx, 1);
                }

            } else if ($scope.branchCategoriesselected.length === 0 || $scope.branchCategoriesselected.length > 0) {
                //move them all in there
                $scope.branchCategoriesselected = ["BranchOpening", "BranchClosing", "BranchSale", "BranchLocationChange"];
              
            }
        };


        $scope.clearAllCodes = function () {
            $scope.selectedHistCodes = [];
            $scope.searchingHistCodes = [];

            var chkboxes = $("#availHistCodes input:enabled").prop('checked', false);
            $scope.getHistoryByDateCounts();
            $scope.doDateOnlySearch = true;
            return false;
        }

        $scope.toggleAllFlag = function () {
            $scope.doDateOnlySearch = !$scope.doDateOnlySearch;
            $scope.getHistoryByDateCounts();
        }

        $scope.checkAndInitEndDate = function (startDate)
        {
            if ($scope.criteria.endDate == null && startDate != null && startDate instanceof Date)
            {
                
                $scope.criteria.endDate = $filter('date')(startDate, 'MM/dd/yyyy');
            }
        }

        $scope.resetForm = function () {
            $state.go('root.adv.history.byDate',null, { reload: true });
        }

        //Branch Category options ===================================================




        function activate() {
            //$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            //    $scope.isIndex = isOnIndexPage(toState);

            //});
            var cssTag = document.createElement("link");
            cssTag.type = "text/css";
            cssTag.rel = "stylesheet";
            cssTag.href = "/content/css/historyByDateSearch.css";
            document.getElementsByTagName("head")[0].appendChild(cssTag);

            //$timeout(function () {
            //    var sdat = $('[id="startDate _input"]');
            //    if (sdat.length > 0) { sdat[0].focus(); }
            //}, 1000);

            window.scrollTo(0, 0);           

            $scope.criteria.searchby = 'byEntryDate';

            // setup watchs to get new counts when the UI changes values
            $scope.$watch('criteria.startDate', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    $scope.checkAndInitEndDate(newValue);
                    $scope.getHistoryByDateCounts();
                }
            });

            $scope.$watch('criteria.endDate', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    $scope.getHistoryByDateCounts();
                }
            });

            $scope.$watch('criteria.searchby', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    $scope.getHistoryByDateCounts();
                }
            });

            //// setup watch for startdate changes
            //$scope.$watch('criteria.startDate', function (newValue, oldValue) {
            //    if (newValue != oldValue && !isNaN(Date.parse(newValue)) && isNaN(Date.parse($scope.criteria.endDate))) {
            //        $scope.criteria.endDate = newValue;     // blank enddate becomes same as startdate
            //    }
            //});            

            HistoryService.getStructureHistoryCodes().then(function (data) {
                $scope.availableHistCodes = data;
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
        }


        function combineTheSelectedOptions(tclist, pclist, bclist)
        {
            //take the 3 selected list items and combine them
            var masterList = tclist.concat(pclist);
            masterList = masterList.concat(bclist);
            console.log('master list ' + masterList);
             return  masterList;

        }        

        function buildTheSelectedOptions(tclist, pclist, bclist) {
            var theList = [];

            _.each(tclist, function (e) {
                if (e == "Acquisitions")
                    theList.push("Tophold Acquisitions");
                else {
                    theList.push(_.find($scope.topCategoryItems, function(cat) {
                         if (cat.id == e) return cat;
                    }).text);
                }
            });
            _.each(pclist, function (e) {
                if (e == "Acquisitions")
                    theList.push("Parent Acquisitions");
                else
                    theList.push(_.find($scope.parentCategoriesItems, function (cat) {
                        if (cat.id == e) return cat;
                    }).text);
            });
            _.each(bclist, function (e) {
                theList.push(_.find($scope.branchCategoriesItems, function(cat) {
                    if (cat.id == e)
                        return cat;
                }).text);
            });

            return theList;
        }

        function buildCreteriaValue(data) {

            $scope.criteriaValue = {
                rssdId: data.RSSDId,
                FDICCert: data.FDICCertNum,
                name: data.OrgName,
                state: data.stateId ? $scope.criteria.state.state : null,
                county: data.countyId ? $scope.criteria.county.county : null,
                city: $scope.criteria.city != null ? $scope.criteria.city.name : null
            }
        }

        function handleHistorybyDateSearch(angularEvent) {
            if ($scope.criteria.startDate == null || $scope.criteria.startDate == null)
            {
                toastr.error("Start Date and End Date are required!");
                return;
            }

            if ($scope.criteria.endDate)
            {
                if (new Date($scope.criteria.startDate) > new Date($scope.criteria.endDate))
                {
                    toastr.error("End date must be equal to, or greater than, the Start Date!");
                    return;
                }
            }            

            var isEntryDate;
            var dateTypeLabel;
            if ($scope.criteria.searchby == 'byEffectiveDate') {
                isEntryDate = false;
                dateTypeLabel = "Transaction";
            }
            else {
                isEntryDate = true;
                dateTypeLabel = "Entry";
            }
            

            var searchData = {
                startDate: $scope.criteria.startDate,
                endDate: $scope.criteria.endDate,
                isEntryDate: isEntryDate,
                historyCodeIds: $scope.selectedHistCodes,
                stateFipsId: $scope.stateFilterId,
                districtId: $scope.districtFilterId,
                brStartSpecId: $scope.brStartSpecId
            };


            $scope.searchCriteria = "<b><span class='strong'>" + dateTypeLabel + "Date of</span> ";
            $scope.searchCriteria += searchData.startDate + (searchData.endDate == undefined ? "" : " - " + searchData.endDate);
            $scope.searchCriteria = $sce.trustAsHtml($scope.searchCriteria);

            $scope.HistorybyDataLoaded = false;
            $scope.HistorybyDateDataLoaded = false;
            $scope.setFilterDdDisplay();
            HistoryService
                .postHistorybyDate(searchData.startDate, searchData.endDate, searchData.historyCodeIds, searchData.isEntryDate, $scope.stateFilterId, $scope.districtFilterId, searchData.brStartSpecId)
                .then(function (data) {
                    angular.forEach(data, function (value, key) { $scope.unfilteredHistoryIds.push(value.historyid) });
                    $scope.HistorybyDateData = data;
                    $scope.HistorybyDateDataLoaded = true;
                    $scope.HistorybyDataLoaded = true;
                    $scope.hideResults = false;
                    var formElement = null;
                    if (angularEvent && angularEvent.currentTarget) { 
                        formElement = $(angularEvent.currentTarget);
                        var scrollToY = ($(formElement).offset().top + $(formElement).height()) - 220;
                        window.scrollTo(0, scrollToY);
                    }
                });
        }
       

        function handleEditHistory(historyId) {
            var data = {
                historyID: $scope.criteria.historyID,
                rSSDId: $scope.criteria.rSSDID,
                name: $scope.criteria.orgName,
                historyCode: $scope.criteria.historyCode,
                transactionDate: $scope.criteria.transactiondate,
                entryDate: $scope.criteria.entryDate,
                historyIsPublic: $scope.criteria.isPublic,
                internalAutoMemo: $scope.criteria.autoMemoInternal,
                publicAutoMemo: $scope.criteria.autoMemoPublic,
                memoText: $scope.criteria.userDefinedMemo,
                copyUserMemoToAll: $scope.criteria.copyUserMemoToAll,
                transDateType: $scope.criteria.transDateType,
            };


            HistoryService
                .postEdiHistory(data.historyID, data.rSSDIDs, data.name, data.historyCode, data.transactionDate, data.entryDate, data.isPublic, data.internalAutoMemo, data.publicAutoMemo, data.memoText, data.copyttosubs, data.marketNumber, data.memo, data.copyUserMemoToAll, data.transDateType)
                .then(function (data) {
                    if (data.errorFlag == false) {
                       toastr.success("History Memo record updated  - " + $scope.criteria.memo + ".");
                        
                        
                    }
                    else
                        toastr.error("There was an unexpected error.", data.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
                    $scope.isReadOnly = true;
                    $scope.HistorybyDataLoaded = true;
                });
        }

        function handleDelHistory(historyId) {
            var data = {
                cascadeDeleteAllRelated: false,
            };

            var confirmDialog = Dialogger.confirm("Are you sure you want to delete these?"); 

            confirmDialog.then(function(confirmed) 
            { 
                if (confirmed) {
                    HistoryService
                       .postDelHistory(historyID, data.cascadeDeleteAllRelated)
                       .then(function (data) {
                           if (data.errorFlag == false) {
                               toastr.success("History Memo delete  - " + $scope.criteria.memo + ".");
                               //reload the history data screen
                               //clear out items
                               //redirect somewhere
                           }
                           else
                               toastr.error("There was an unexpected error.", data.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
                           //$scope.isReadOnly = true;
                           //$scope.HistorybyDataLoaded = true;
                       });
                }
            });
        }
        


        $scope.printView = function () {
            // determine the type of search to do
            var isEntryDate;
            var dateTypeLabel;
            if ($scope.criteria.searchby == 'byEffectiveDate') {
                isEntryDate = false;
                dateTypeLabel = "Transaction";
            }
            else if ($scope.criteria.searchby == 'byEntryDate') {
                isEntryDate = true;
                dateTypeLabel = "Entry";
            }
            else {
                isEntryDate = null;
                dateTypeLabel = "Transaction or Entry";
            }

            var data = [
                $scope.criteria.startDate,
                $scope.criteria.endDate ,
                isEntryDate,
                false,
                [],
                $scope.selectedHistCodes,
                $scope.stateFilterId,
                $scope.districtFilterId
            ];
            var reportType = 'searchbydatehistory';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }

        $scope.showChangeRecDoc = function (docUrl) {
            if (!docUrl || docUrl == "") {
                return false;
            }
            var winWidth = window.innerWidth * 0.75;
            var winHeight = window.innerHeight * 0.8;
            var recordDocWin = window.open(docUrl, 'recordDocWin', 'location=yes,height=' + winHeight + ',width=' + winWidth + ',scrollbars=yes,status=yes');
            return false;
        }

        $scope.submitFilterForm = function () {
            var frm = $("#historyByDateForm");
            if (frm && frm.length == 1) {
                frm[0].submit();
            }
        }
    }
})();
 
;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('HistoryService', HistoryService);

    HistoryService.$inject = ['$http', '$log'];

    function HistoryService($http, $log) {
        var service = {
            getStructureHistoryCodes: getStructureHistoryCodes,
            getHistorybyMarkets: getHistorybyMarkets,
            getMemoMarketHistory: getMemoMarketHistory,
            postupdateMarketHistory: postupdateMarketHistory,
            postDelInstHistory: postDelInstHistory,
            postMarketDelHistory: postMarketDelHistory,
            getHistorybyInst: getHistorybyInst,
            postHistorybyDate: postHistorybyDate,
            postaddHistory: postaddHistory,
            getMarketNumberList: getMarketNumberList,
            getGetInstHistory: getGetInstHistory,
            postupdateInstHistory: postupdateInstHistory,
            getStructureAdjustedReport: getStructureAdjustedReport,
            hasAdjustedReport: hasAdjustedReport,
            getHistoryByDateCounts: getHistoryByDateCounts
        };

        return service;
        ////////////////
        function getStructureHistoryCodes() {
            return $http.get('/api/history/structure-history-codes')
                .then(function Success(result) {
                   // $log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History Code list", result);
                });
        }     

        function getHistoryByDateCounts(startDate, endDate, isEntryDate, historyCodeIds, stateFipsId, districtId) {
            return $http.post('/api/history/history-by-date-counts', { startdate: startDate, enddate: endDate, isEntryDate: isEntryDate, historyCodeIds: historyCodeIds, stateFipsId: stateFipsId, districtId: districtId })
                .then(function Success(result) {
                    // $log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting history by date counts", result);
                });
        }

        function getHistorybyMarkets(stateId, MarketNumber, Name, County, CityName, Zip) {
            return $http.get('/api/history/history-by-market', { params: { stateId: stateId, MarketNumber: MarketNumber, Name: Name, countyid: County, CityName: CityName, Zip: Zip } })
                .then(function Success(result) {
                   // $log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History by Markets data", result);
                });
        }
        function getMemoMarketHistory(marketHistoryMemoId) {

            return $http.get('/api/history/market-hist-memo', { params: { marketHistoryMemoId: marketHistoryMemoId } })
                .then(function Success(result) {
                    //$log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning get History Memo Transaction", result);
                });
        }
        function getHistorybyInst(RSSDId, FDICCertNum, OrgName, stateId, county, city, district) {
            return $http.get('/api/history/history-by-inst', { params: { RSSDId: RSSDId, FDICCertNum: FDICCertNum, OrgName: OrgName, stateId: stateId, countyid: county, cityName: city, districtId: district } })
                .then(function Success(result) {
                   // $log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History by Inst data", result);
                });
        }
        function getGetInstHistory(structHistoryMemoId) {

            return $http.get('/api/history/get-history', { params: { structHistoryMemoId: structHistoryMemoId } })
                .then(function Success(result) {
                    //$log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History get History Transaction", result);
                });
        }
        function getStructureAdjustedReport(institutionRSSDId) {

            return $http.get('/api/history/get-structureAdjusted-report', { params: { institutionRSSDId: institutionRSSDId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning Structure - Adjusted History Report", result);
                });
        }
        function hasAdjustedReport(institutionRSSDId) {

            return $http.get('/api/history/has-adjusted-report', { params: { institutionRSSDId: institutionRSSDId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning Adjusted History Report", result);
                });
        }

        function postHistorybyDate(startdate, enddate, historyCodeIds, isEntryDate, stateFipsId, districtId, brStartSpecId) {
            var data = {
                startDate: startdate,
                endDate: enddate,
                historyCodeIds: historyCodeIds,
                isEntryDate: isEntryDate,
                stateFipsId: stateFipsId,
                districtId: districtId,
                brStartSpecId: brStartSpecId
            };

            return $http.post('/api/history/history-by-date', data)
                .then(function Success(result) {
                   
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History by Date data", result);
                });
        }

        function postaddHistory(historyCode, transactionDate, entryDate, isPublic, rSSDIDs, copyttosubs, marketNumber, memo, changePacketId) {
            var data = {
                historyCode: historyCode,
                transactionDate: transactionDate,
                entryDate: entryDate,
                isPublic: isPublic,
                rSSDIDs: rSSDIDs,
                copyttosubs: copyttosubs,
                marketNumber: marketNumber,
				memo: memo,
				changePacketId: changePacketId
            };
            return $http.post('/api/history/add-history', data)
                .then(function Success(result) {
                    $log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History add History Transaction", result);
                });
        }

       
      

        function postDelInstHistory(historyData) {
            var data = {
                structHistoryMemoId: historyData.historyRecord.structureHistoryMemoId,
                cascadeDeleteAllRelated: historyData.cascadeDeleteAllRelated
            };
            //structHistoryMemoId, cascadeDeleteAllRelated
            return $http.post('/api/history/del-history', data)
                .then(function Success(result) {
                    //$log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History delete History Transaction", result);
                });
        }
        function postMarketDelHistory(historyData) {
            var data = {
                marketHistoryMemoId: historyData.historyRecord.marketHistoryMemoId,
                cascadeDeleteAllRelated: historyData.cascadeDeleteAllRelated
            };

            return $http.post('/api/history/del-market-history', data)
                .then(function Success(result) {
                    $log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History delete History Transaction", result);
                });
        }



        function getMarketNumberList(RSSDId ) {
            return $http.get('/api/history/market-number-list', { params: { RSSDId: RSSDId } })
                .then(function Success(result) {
                    $log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market number lsit", result);
                });
        }
        function postupdateInstHistory(historyData) {
            var data = {
                historyRecord: historyData.historyRecord,
                copyUserMemoToAll: historyData.copyUserMemoToAll,
                transDateType: historyData.transDateType,
            };



            return $http.post('/api/history/edit-history', data)
                .then(function Success(result) {
                    //$log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History update History Transaction", result);
                });
        }
        function postupdateMarketHistory(historyData) {
            var data = {
                historyRecord: historyData.historyRecord,
                copyUserMemoToAll: historyData.copyUserMemoToAll,
                transDateType: historyData.transDateType,
            };

            return $http.post('/api/history/edit-market-history', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History update History Transaction", result);
                });
        }

    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('WelcomeController', WelcomeController);

    WelcomeController.$inject = ['$scope', '$http', '$uibModal', 'AdvancedNewsService', '$log'];

    function WelcomeController($scope, $http, $uibModal, News, $log) {

        angular.extend($scope, {
            releaseNotes: [],
            hasReleaseNotes: checkIfReleaseNotes,
            news: [],
            hasNews: checkIfNews,
            dismiss: dismissNewsItem,
            content: '',
            contentReady: false
        });

        var defaultNewsScrollInterval = 10000;
        $scope.newsScrollInternval = defaultNewsScrollInterval;

        activate();

        function activate() {

            // Welcome Content
            News.query("WELCOME_ADVANCED", 1).then(function (result) {
				if (result && result.length > 0) {
					$scope.content = News.format(result[0].body);
				}
                $scope.contentReady = true;

            });

            News.query("RELEASE_NOTES", 6).then(function (result) {

                _.each(result, function (item) {
                    item.created = item.created.split('T')[0];
                    item.details = News.parseNotes(item.body);
                });

                $scope.releaseNotes = _.filter(result, function (item) { return _.indexOf(dismissedIds, item.newsId) === -1; });
            });

            // News
            var dismissedIds = News.getDismissedNewsIds();
            //$log.warn("dismissedIds", dismissedIds);

            News.query("ADVANCED_NEWS", 6).then(function (result) {
                $scope.news = _.filter(result, function (item) { return _.indexOf(dismissedIds, item.newsId) === -1; });
            });
        }

        function checkIfReleaseNotes() {
            return $scope.releaseNotes && $scope.releaseNotes.length > 0;
        }        

        $scope.setNewsScrolling = function (isScrolling) {
            if (isScrolling) {
                $scope.newsScrollInternval = defaultNewsScrollInterval;
            }
            else { $scope.newsScrollInternval = false; }
        }

        function checkIfNews() {
            return _.filter($scope.news, function (item) { return !item.dismissed; }).length > 0;
        }

        function dismissNewsItem(item) {
            News.dismissByNewsId(item.newsId);
            item.dismissed = true;
        }

    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvBranchCloseController', AdvBranchCloseController);

	AdvBranchCloseController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', '$uibModal', 'toastr', 'uibDateParser', '$timeout', 'AdvBranchesService', 'AdvMarketsService', 'Dialogger'];

	function AdvBranchCloseController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, $uibModal, toastr, uibDateParser, $timeout, AdvBranchesService, AdvMarketsService, Dialogger) {

        $scope.instData = [];
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
        $scope.criteria = [];
		$scope.processing = false;
		$scope.returnToBrList = false;
		$scope.returnToSearch = false;
		$scope.criteria.packetId = null;
        $scope.criteria.transactionDateType = 2;
        $scope.roadDistance = null;
        $scope.moveToCuRssd = null;


        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

            var d = new Date();

            if ($scope.criteria == null || !$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.transactionDateType) {
                toastr.error("Transaction Type must be entered!");
                $scope.contProcessing = false;
            }

            // check to see if the branches parent has other branches if they are just doing a payout
            if ($scope.mode == 'BranchDepositTransfer' || $scope.mode == 'BranchDepositTransferNewTransfer') {
                Dialogger.confirm('You are closing Branch ' + $scope.closingBranch.facility + ' and transferring deposits to Branch ' + $scope.transfertoBranch.facility + '.  Do you want to continue?', null, true).then(function (result) {
                    $scope.contProcessing = result;
                    if ($scope.contProcessing == true) {
                        processBranchCloseDepositTransfer();
                    }
                });
            }
            else {
                if ($scope.contProcessing == true) {

                    $scope.processing = true;

                    //check to see if there is any branches that are close.  If there is just tell them that there are.
                    AdvBranchesService.getNearestBranches($scope.closingBranch.branchId, 6).then(function (result) {

                        $scope.processing = false;

                        $scope.nearestData = result;
                        if (result) {
                            //check to see if they are closing the head office, if they are tell them they cannot and they need to make another branch the head office.
                            if ($scope.closingBranch.facility == 0) {
                                toastr.error('You cannot close the head office.  You must first assign a different branch as the head office.');
                                return;
                            }
                            else {
                                Dialogger.confirm('You are closing Branch ' + $scope.closingBranch.facility + ' and still have branches remaining in the banking market.  Do you want to continue?', null, true).then(function (nearresult) {
                                    $scope.contProcessing = nearresult;
                                    if ($scope.contProcessing == true && $scope.moveToCuRssd) {
                                        Dialogger.confirm('The closed branch will be Purchased by Credit Union RSSDID ' + $scope.moveToCuRssd + '. Do you want to continue?', null, true).then(function (okToContinue) {
                                            $scope.contProcessing = okToContinue;
                                            if ($scope.contProcessing) {
                                                // check RSSD is valid CU
                                                AdvInstitutionsService.getIsCURssd($scope.moveToCuRssd).then(
                                                    function (cuCheckResult) {
                                                        if (!cuCheckResult) {
                                                            toastr.error("Invalid Credit Union RSSD Id!");
                                                        }
                                                        else {
                                                            processBranchCloseDepositPayout(false);
                                                        }
                                                    }
                                                )                                              
                                            }
                                        });
                                    }
                                    else {
                                        if ($scope.contProcessing) {
                                            processBranchCloseDepositPayout(false);
                                        }
                                    }
                                });
                            }
                        }
                        else {
                            //we have no other branches so ask if they want to close the bank/thrift
                            Dialogger.confirm('You are closing Branch ' + $scope.closingBranch.facility + ' .  Do you want to continue?', null, true).then(function (closingresult) {
                                if (closingresult == true) {
                                    if ($scope.closingBranch.facility == 0)
                                    {
                                        Dialogger.confirm('Is the Institution closing?', null, true).then(function (closingBankresult) {
                                            processBranchCloseDepositPayout(closingBankresult);
                                        });
                                    }
                                    else
                                    {
                                        processBranchCloseDepositPayout(false);
                                    }
                                    
                                }
                            });

                        }
                    });
                    
                    
                }
            }
        };        

        $scope.gotoBranchList = function () {
            $state.go('root.adv.institutions.summary.orgs', { rssd: $scope.closingBranch.parentRssdId });
            $scope.$dismiss();
        }

        $scope.gotoBranchSearchList = function () {
            $state.go('root.adv.institutions.branchreport');
            $scope.$dismiss();
        }          

		$scope.gotoInstSearchForm = function () {
			$state.go('root.adv.institutions.instsearch');
			$scope.$dismiss();
		} 
		
        $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /^(\d{5}-\d{4}|\d{5})$/;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();

            }
        };

       


        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }


        function processBranchCloseDepositTransfer() {
            var branchCloseTransferInfo = {
                closeBranchID: $scope.closingBranch.branchId,
                transferBranchID: $scope.transfertoBranch.branchId,
                transDate: $scope.criteria.historyTransactionDate,
				transType: $scope.criteria.transactionDateType,
				firmaPacketId: $scope.criteria.packetId 
            }

            AdvBranchesService.postBranchDepositTransferClose(branchCloseTransferInfo)
             .then(function (result) {
                 if (!result.errorFlag) {
                     $scope.displayConfirmation = true;
                     $scope.instDataReady = false;
					 $scope.Instchanged = true;
					 $scope.returnToBrList = true;
                 }
                 else {
                     if (result.messageTextItems.length > 0) {
                         for (var i = 0; i < result.messageTextItems.length; i++) {
                             toastr.error(result.messageTextItems[i]);
                         }
					 }
					 $scope.returnToBrList = false;
                 }
             });


        }

        function processBranchCloseDepositPayout(closeBank) {
            var branchCloseTransferInfo = {
                closeBranchID: $scope.closingBranch.branchId,
                transDate: $scope.criteria.historyTransactionDate,
                transType: $scope.criteria.transactionDateType,
				hasFailedParent: closeBank,
				firmaPacketId: $scope.criteria.packetId

            }

            $scope.processing = true;

            AdvBranchesService.postBranchDepositClose(branchCloseTransferInfo, $scope.moveToCuRssd)
                .then(function (result) {

                 $scope.processing = false;

                 if (!result.errorFlag) {
                     $scope.displayConfirmation = true;
                     $scope.instDataReady = false;
                     $scope.Instchanged = true;
                     if ($scope.closingBranch.facility == 0) {
                         if (closeBank == true) {
                             processClosetheBank();
                         }
					 }
					 $scope.returnToBrList = true;
                 }
                 else {
                     if (result.messageTextItems.length > 0) {
                         for (var i = 0; i < result.messageTextItems.length; i++) {
                             toastr.error(result.messageTextItems[i]);
                         }
					 }
					 $scope.returnToBrList = false;
                 }
             });


        }



        function processClosetheBank() {

            //load the temp version of the bank that is closing
            AdvInstitutionsService.getInstitutionData({ rssdId: $scope.closingBranch.parentRssdId, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
            .then(function (instData) {
                //now populate the Tophold 
                $scope.bankclosed = instData.definition;

                var instUpdDTO =
             {
                 Id: $scope.criteria.id,
                 RSSDId: $scope.closingBranch.parentRssdId,
                 InstitutionRSSDId: $scope.closingBranch.parentRssdId,

             }

                var id = $scope.criteria.id;


                var data = {
                    instRecord: instUpdDTO,
                    cascadeToHomeBranch: false,
                    bypassHistory: false,
                    transDate: $scope.criteria.historyTransactionDate,
					transType: 2,
					firmaPacketId: $scope.criteria.packetId
                }

                AdvInstitutionsService.postcloseInstitution(data).then(function (results) {
                    if (results.errorFlag == true) {
                        //var errorMessage = [];
                        if (results.messageTextItems.length > 0) {
                            for (var i = 0; i < results.messageTextItems.length; i++) {
                                toastr.error('There was an error Closing the Parent Institution ' + results.messageTextItems[i]);
                            }
						}
						$scope.returnToSearch = false;
                    }
                    else {
						$scope.CloseInst = true;
						$scope.returnToSearch = true;
                    }
                }, function (err) {
                    alert("Sorry. There was an error.");
                });


            });
            

        }

        $scope.cancel = function () {
 			$scope.$dismiss();
			if ($scope.returnToBrList) {
				$scope.gotoBranchList();
			}
			else if ($scope.returnToSearch) {
				$scope.gotoInstSearchForm();
			}
			else {
				$state.reload();
			}
        };

        $scope.populatetransfertFacInfo = function() {
            //populate the transfer branch object
            AdvBranchesService.getBranchbyBranchNum($scope.closingBranch.parentRssdId,$scope.criteria.facility).then(function (result) {
                if (result && result != null) {
                    $scope.transfertoBranch = result;
                    $scope.TotalDeposits = $scope.closingBranch.deposits + $scope.transfertoBranch.deposits
                }
            });

        }

        activate();

        function activate() {
            //move to the top of the screen and set focus on the RSSDID

            // 04/19/2019 - This raises an error and I see no reason to have this call
            //$timeout(function () {
            //    $('[id="historyTransactionDate _input"]')[0].focus();

            //}, 750);

			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}

            window.scrollTo(0, 0);
            $scope.roadDistance = $state.params.roadMiles;

            //so where are we coming from.
            //if the params have a branchid and then a transfer to branchid then default to deposit transfer

            //So if we come from the Find Nearest Branch level and are looking transfer from the view branch to the selected branch
            if ($state.params.mode == 'BranchDepositTransfer') 
            {
                //we need to populate the screen
                $scope.closingBranch = $state.params.closingBranch;
                
                //populate the transfer branch object
                $scope.processing = true;
                AdvBranchesService.getBranchDetail({ branchId: $state.params.transfertoBranch.id }).then(function (result) {
                    $scope.processing = false;
                    if (result && result != null) {
                        $scope.transfertoBranch = result;
                        $scope.TotalDeposits = $scope.closingBranch.deposits + $scope.transfertoBranch.deposits
                    }
                });

                $scope.pageTitle = "Branch Closed - Depositor Transfer";
                $scope.mode = $state.params.mode;
                //populated the screen correctly
                $scope.instDataReady = true;
                $scope.Instchanged = false;



            }
            else if ($state.params.mode == 'BranchDepositTransferNewTransfer') {
                //we need to populate the screen
                $scope.closingBranch = $state.params.closingBranch;

                ////populate the transfer branch object
                //AdvBranchesService.getBranchDetail({ branchId: $state.params.transfertoBranch.id }).then(function (result) {
                //    if (result && result != null) {
                //        $scope.transfertoBranch = result;
                //        $scope.TotalDeposits = $scope.closingBranch.deposits + $scope.transfertoBranch.deposits
                //    }
                //});

                $scope.pageTitle = "Branch Closed - Depositor Transfer";
                $scope.mode = $state.params.mode;
                //populated the screen correctly
                $scope.instDataReady = true;
                $scope.Instchanged = false;



            }
                //So if we come from the action icon on the this is just doing a payout, check to see if there are other branches for this parent. 
                //if so prompt the user and let them decided
            else if ($state.params.mode == 'BranchDepositPayout') 
            {
                $scope.closingBranch = $state.params.closingBranch;

                $scope.pageTitle = "Branch Closed - Depositor Payoff";

                
                $scope.mode = $state.params.mode;
                //populated the screen correctly
                $scope.instDataReady = true;
                $scope.Instchanged = false;
            }
            else
            {
                //how did we get there hmm


            }




            

                           



        }

}
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('AdvBranchesService', AdvBranchesService);

    AdvBranchesService.$inject = ['$http', '$log', '$uibModal'];

    function AdvBranchesService($http, $log, $uibModal) {
        var service = {
            getBranchesInRect: getBranchesInRect,
            getBranchSearchData: getBranchSearchData,
            getSpecialityFlags: getSpecialityFlags,
            getLocatorStatuses: getLocatorStatuses,
            getBranchId: getBranchId,
            getBranchDetail: getBranchDetail,
            getBranchEditDetail: getBranchEditDetail,
            getBranchGeoCode: getBranchGeoCode,
            postupdateBranch: postupdateBranch,
            postupdateGeocode: postupdateGeocode,
            addOrEditBranch: addOrEditBranch,
            postBranchClose: postBranchClose,
            postBranch: postBranch,
            postaddBranch: postaddBranch,
            getNearestBranches: getNearestBranches,
            getNearestBranchesForMap: getNearestBranchesForMap,
            checkRSSDIDIsTophold: checkRSSDIDIsTophold,
            postBranchDepositTransferClose: postBranchDepositTransferClose,
            postBranchDepositClose: postBranchDepositClose,
            openEditGeocodeForm: openEditGeocodeForm,
            getBranchbyBranchNum: getBranchbyBranchNum,
            getInstitutionName: getInstitutionName,
            getSpecialityFlag: getSpecialityFlag,
            getSpecBranchesFromPoint: getSpecBranchesFromPoint,
            getBranchToMarketBranchDistance: getBranchToMarketBranchDistance
        };

        return service;
        ////////////////

		function getBranchSearchData(data) {
            return $http.get('/api/advinstitutions/branch-search', { params: { marketNumber: data.marketNumber, state: data.state, county: data.county, cityName: data.cityName, zip: data.zip, customMarket: data.customMarket, parentRssdId: data.parentRssdId, fdic: data.fdicId, msa: data.msa, districtId: data.districtId, entityType: data.entityType } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }

   
        function getBranchId(data) {
            return $http.get('/api/advinstitutions/get-branchId', { params: { cassidiId: data.cassidiId, firmatId: data.firmatId, uninumber: data.uninumber, branchRssdId: data.branchRssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning rssd data", result);
                });
        }
        function getBranchDetail(data) {
            return $http.get('/api/advinstitutions/get-branch-detail', { params: { branchId: data.branchId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning rssd data", result);
                });
        }

        function getBranchbyBranchNum(parentRSSDID, branchNum) {
            return $http.get('/api/advinstitutions/get-branch-by-branchNum', { params: { parentRSSDID: parentRSSDID, branchNum: branchNum } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning branch details data", result);
                });
        }

        


        function getBranchEditDetail(data) {
            return $http.get('/api/advinstitutions/get-branch-edit', { params: { branchId: data.branchId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning rssd data", result);
                });
        }

        function getBranchGeoCode(data) {
            return $http.get('/api/advinstitutions/get-branch-geocode', { params: { branchId: data.branchId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning geocode data", result);
                });
        }


        function getSpecialityFlags(includeLegacyNoneVal) {
            if (typeof includeLegacyNoneVal === 'undefined') { includeLegacyNoneVal = true }
            return $http.get('/api/advinstitutions/get-specialityFlags', { params: { includeLegacy: includeLegacyNoneVal } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning speciality flag data", result);
                });
        }
        function getSpecialityFlag(data) {
           
            return $http.get('/api/advinstitutions/get-specialityFlag', { params: { specialityFlagId:data.specialityFlagId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning speciality flag data", result);
                });
        }
        function getLocatorStatuses() {
            return $http.get('/api/advinstitutions/get-locatorStatuses')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning locator status data", result);
                });
        }

        function getInstitutionName(rssdId)
        {
            return $http.get('/api/advinstitutions/get-institution-name', { params: { institutionRSSDId: rssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning locator status data", result);
                });
        }
            

        function postupdateBranch(branchData) {
            return $http.post('/api/advinstitutions/edit-branch', branchData)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error saving branch data", result);
                });
        }

        function postaddBranch(branchData) {
            var data = {
                branchRecord: branchData.branchRecord,
                bypassHistory: branchData.bypassHistory,
                transDate: branchData.transDate,
                transType: branchData.transType,
				isFromBankCharter: branchData.isFromBankCharter,
                firmaPacketId: branchData.firmaPacketId,
                latitude: branchData.latitude,
                longitude: branchData.longitude
            };
            return $http.post('/api/advinstitutions/add-branch', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error saving branch data", result);
                });
        }

        function postupdateGeocode(geoData) {
            return $http.post('/api/advinstitutions/edit-geocode', geoData)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error saving GeoCode branch data", result);
                });
        }


        function getSpecBranchesFromPoint(centerLat, centerLng, parentRssdId, maxToReturn = 10, radiusMeters = 305, brSpecId = null) {
            var data = { 'centerLat': centerLat, 'centerLng': centerLng, 'parentRssdId': parentRssdId, 'maxToReturn': maxToReturn, 'radiusMeters': radiusMeters, 'brSpecId': brSpecId};
            return $http.post('/api/advinstitutions/get-nearest-br-from-point', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting nearest specialty branches", result);
                });

        }

        //decimal centerLat, decimal centerLng, int parentRssdId, int maxToReturn = 10, int radiusMeters = 305, int ? brSpecId = null


        function addOrEditBranch(branchId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_branch.html',
                controller: 'AdvInstitutionsEditBranchController',
                resolve: {
                    branchId: function () {
                        return branchId;
                    }
                }
            }); 

           
        }


        function postBranchClose(branchId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_branchClosed.html',
                controller: 'AdvBranchCloseController',
                resolve: {
                    branchId: function () {
                        return branchId;
                    }
                }
            });


        }


           
       
        function postBranch(branchId, data) {
            return branchId ? postupdateBranch(data) : postaddBranch(data);
        }


        function getNearestBranches(branchId, count) {
            return $http.get('/api/advinstitutions/get-nearest', { params: { branchId: branchId, count: count } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning nearest branch data", result);
                });
        }

        function getNearestBranchesForMap(branchId, count, meters) {
            
            return $http.get('/api/advinstitutions/get-nearest-map', { params: { branchId: branchId, count: count, meters: meters } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning nearest branch data", result);
                });
        
        }

        function getBranchesInRect(topLeftLatitude, topLeftLongitude, bottomRightLatitude, bottomRightLongitude) {

            return $http.get('/api/advinstitutions/get-nearest-map-all', { params: { topLeftLatitude: topLeftLatitude, topLeftLongitude: topLeftLongitude, bottomRightLatitude: bottomRightLatitude, bottomRightLongitude: bottomRightLongitude } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning nearest branch data", result);
                });

        }

        function checkRSSDIDIsTophold(data) {
            return $http.get('/api/advinstitutions/tophold-by-id', { params: { rssdId: data.parentRssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }

        function postBranchDepositClose(data, moveToCURssd) {
            if (moveToCURssd && !isNaN(moveToCURssd)) {
                data.moveToCURssd = moveToCURssd;
            }
            return $http.post('/api/advinstitutions/close-branch', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error processing the Branch Close", result);
                });
        }

        function postBranchDepositTransferClose(data) {
            return $http.post('/api/advinstitutions/close-deposit-transfer-branch', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error processing the Branch Close and Deposit Transfer", result);
                });
        }

       function openEditGeocodeForm(branchid) {
           
            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_BranchGeocode.html',
                controller: 'AdvInstitutionsEditBranchGeocodeController'
            });
        };

        function getBranchToMarketBranchDistance(branchId) {
            return $http.get('/api/advinstitutions/branchtomarketbranchdistances', { params: { branchId: branchId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting distance between branches", result);
                });
        }

    }
})();
;
/// <reference path="AdvInstitutionsListController.js" />

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvFindInstForAquiringbyTophold', AdvFindInstForAquiringbyTophold);

    AdvFindInstForAquiringbyTophold.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', 'Dialogger', 'toastr', 'uibDateParser', 'AdvPendingService', '$timeout', 'AdvBranchesService', 'genericService'];


    function AdvFindInstForAquiringbyTophold($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, Dialogger, toastr, uibDateParser, AdvPendingService, $timeout, AdvBranchesService, genericService) {
 
         

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            processchange()
        };


        $scope.getRSSDID = function () {
            var data =
            {
                RssdId: $scope.criteria.InstRssdId
            }


           
        };

         $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /^[0-9]$/;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();

            }
         };

        $scope.cancel = function () {

            $scope.$dismiss();
            //$state.go('root.adv.institutions.instsearch', $scope.reloadData, { reload: true });
            //$state.('root.adv.institutions.summary', { rssd: $scope.criteria.rssdId, isTophold: true });
            $state.go;
        };


        function processchange() {
                var rssd
                rssd = $scope.criteria.InstRssdId

                $state.params.rssd = rssd;
                $state.params.newTopHoldRSSDID = $state.params.TopHoldrssdId;
                $state.params.TransactionDate = $state.params.historyTransactionDate;


                $scope.$dismiss();

                $state.go;

                AdvInstitutionsService.postAcquiredByTophold(rssd.RssdId);

                
            
        }

        

      

        


        activate();

        function activate() {
            //move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                $('[id="rssdId"]').focus();

            }, 750);

            window.scrollTo(0, 0);
          

           


          


        }





    }
})();;
/// <reference path="AdvInstitutionsListController.js" />

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstAcquiredByTophold', AdvInstAcquiredByTophold);

    AdvInstAcquiredByTophold.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', 'Dialogger', 'toastr', 'uibDateParser', 'AdvPendingService', '$timeout', 'AdvBranchesService','genericService'];


    function AdvInstAcquiredByTophold($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, Dialogger, toastr, uibDateParser, AdvPendingService, $timeout, AdvBranchesService, genericService) {
        $scope.txnIds = [];
        $scope.runDate = new Date();
		$scope.pendingReady = true;
		$scope.criteria = [];
		$scope.criteria.packetId = null;

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;
            var d = new Date();
            //verify we have transaction date, name, primary 

			$scope.entrydate = d;

			//verify that we have a change packet selected
			if ($rootScope.FeatureToggles.ChangePacketIntegration && (!$scope.criteria.packetId || typeof ($scope.criteria.packetId) != "number")) {
				toastr.error("Change packet must be selected!");
				$scope.contProcessing = false;
			}

            //verify we have transaction date, name, primary 
            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.transactionDateType) {
                toastr.error("Transaction Type must be entered!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.newParentRSSDId) {
                toastr.error("New Tophold RSSDID required!");
                $scope.contProcessing = false;
            }

            if ($scope.contProcessing == true) {

                //if this is a controlled acquire then get the old $scope.criteria.parentTopholdRSSDId
                if ($scope.criteria.parentTopholdRSSDId != $scope.criteria.RSSDId) {
                    AdvInstitutionsService.getEditTopholdData({ rssdId: $scope.criteria.parentTopholdRSSDId }).then(function (resultOldTH) {
                        if (resultOldTH && resultOldTH != null) {
                            $scope.OldTHcriteria = resultOldTH;
                            if (resultOldTH.stateId > 0) {
                                $scope.OldTHcriteria.state = _.find($scope.states, { stateId: resultOldTH.stateId });
                                genericService.getCounties(resultOldTH.stateId).then(function (resultCounty) {
                                    $scope.OldTHcriteria.state.counties = resultCounty;

                                    $scope.OldTHcriteria.county = _.find($scope.OldTHcriteria.state.counties, { countyId: resultOldTH.countyId });

                                    var dataCity = {
                                        stateId: resultOldTH.stateId,
                                        countyId: resultOldTH.countyId
                                    }
                                    genericService.getCities(dataCity).then(function (resultCity) {
                                        $scope.OldTHcriteria.state.cities = resultCity;
                                        $scope.OldTHcriteria.city = _.find($scope.OldTHcriteria.state.cities, { cityId: resultOldTH.cityId });

                                    });
                                });
                               
                            }
                            else {
                                StatesService.getInternationalCities().then(function (data) {
                                    $scope.internationalCities = data;
                                    $scope.OldTHcriteria.city = _.find($scope.internationalCities, { cityId: resultOldTH.cityId });
                                });
                                
                            }
                            
                        }
                    });
                }

                //lookup the Tophold info
                AdvInstitutionsService.getEditTopholdData({ rssdId: $scope.criteria.newParentRSSDId }).then(function (resultTH) {
                    if (resultTH && resultTH != null) {
                        //populate the tophold information
                        $scope.THcriteria = resultTH;
                        if (resultTH.stateId > 0) {
                            $scope.THcriteria.state = _.find($scope.states, { stateId: resultTH.stateId });

                            genericService.getCounties(resultTH.stateId).then(function (resultCounty) {
                                $scope.THcriteria.state.counties = resultCounty;

                                $scope.THcriteria.county = _.find($scope.THcriteria.state.counties, { countyId: resultTH.countyId });

                                var dataCity = {
                                    stateId: resultTH.stateId,
                                    countyId: resultTH.countyId
                                }
                                genericService.getCities(dataCity).then(function (resultCity) {
                                    $scope.THcriteria.state.cities = resultCity;
                                    $scope.THcriteria.city = _.find($scope.THcriteria.state.cities, { cityId: resultTH.cityId });

                                });
                            });


                        }
                        else
                        {
                            StatesService.getInternationalCities().then(function (data) {
                                $scope.internationalCities = data;
                                $scope.THcriteria.city = _.find($scope.internationalCities, { cityId: resultTH.cityId });
                            });


                            
                            

                            

                            
                        }
                        

                        if ((resultTH.entityTypeCode == 'THC' || resultTH.entityTypeCode == 'SLHC') && ($scope.criteria.entityTypeCode != 'THRIFT')) {
                            Dialogger.confirm('The acquiring Tophold is a SLHC,  Do you want to continue?', null, true).then(function (result) {
                                $scope.contProcessing = result;
                                if ($scope.contProcessing == true) {
                                    processchange();
                                }
                            });
                        }
                        else {
                            if ($scope.contProcessing == true) {
                                processchange();
                            }
                        }
                    }
                    else
                    {
                        toastr.error("Invalid New Tophold RSSDID!");

                    }
                });




               

              
            }
        };


        $scope.getRSSDID = function () {
            var data =
            {
                SurvivorRssdId: $scope.criteria.newParentRSSDId,
                NonSurvivorRssdId: $scope.criteria.parentTopholdRSSDId
            }

            
            $scope.pendingReady = false;
            AdvPendingService.getPendingTHAcqTH(data).then(function (result) {
                if (result) {
                    if (result.length != 0)
                    {
                        $scope.tophold = result;
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = true;
                    }
                    else
                    {
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = false;
                    }
                }
                else {
                    $scope.pendingReady = true;
                    $scope.showPendingTransactions = false;
                }
                $scope.pending = true;
            });
        };

        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = [];
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

        $scope.toggle = function (id, rssdid, memo, selectedPend) {
            $scope.txnIds = [];
            $scope.txnIds.push(id);

            $scope.criteria.pendingtransactionRSSDID = rssdid;
            $scope.criteria.pendingtransactionmemo = memo;
            $scope.criteria.selectedPend = selectedPend;


        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };


        function processchange()
        {
            if ($scope.contProcessing == true) {
                //send the new Tophold to the services later
                // function postInstitution(id, inst) {
                var bankAcquireByTopHold =
                    {
                        buyerRSSDId: $scope.criteria.newParentRSSDId,
                        targetRSSDId: $scope.criteria.rssdId,
                        transactionDate: $scope.criteria.historyTransactionDate,
						transDateType: $scope.criteria.transactionDateType,
						firmaPacketId: $scope.criteria.packetId
                    }
                process(bankAcquireByTopHold);
            }
        }

        function process(data)
        {
			AdvInstitutionsService.postInstAcquiredByTopHold(data)
                        .then(function (data) {
                            //did we have success if yes then we need to do something
                            if (data.errorFlag == false) {

                                        AdvInstitutionsService.getInstitutionData({ rssdId: $scope.criteria.rssdId, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                                            .then(function (instData) {
                                                //now populate the Tophold 
                                                AdvPendingService.getDeletedTransactions($scope.txnIds).then(function (result) {
                                                    toastr.success("Successfully acquired by Tophold");
                                                    toastr.success(result.errorMessage);
                                                    $scope.showPendingTransactions = false;
                                                    $log.info(instData);
                                                    $scope.postcriteria = instData.definition;
                                                });
                                               
                                               
                                            });

                                        $scope.ReadyToAcquire = false;
                                        $scope.Doneacquiring = true;

                                  
                            }
                            else
                            {
                                if (data.messageTextItems.length > 0) {
                                    for (var i = 0; i < data.messageTextItems.length; i++) {
                                        toastr.error(data.messageTextItems[i]);
                                    }
                                }
                            }
                        });

           
        }

        $scope.populateTHWeight = function () {
            AdvInstitutionsService.getEditTopholdData({ rssdId: $scope.criteria.newParentRSSDId }).then(function (THresult)
            {
                if (THresult) {
                    if (THresult.entityTypeCode == 'SLHC' || THresult.entityTypeCode == 'THC') {
                        if ($scope.criteria.orgEntityCodeId == 12) {
                            $scope.criteria.hhiWeight = '1';
                        }
                        else {
                            $scope.criteria.hhiWeight = '.5';
                        }                        
                    }
                    else if (THresult.entityTypeCode == 'BHC') {
                        $scope.criteria.hhiWeight = '1';
                    }
                }
                
                $scope.getRSSDID();
            });
        };
       
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        // this is hacky, replace with better solution
        $scope.showCancel = function () {

            return !$rootScope.isInWizard && $scope.$dismiss != null;

        };


        $scope.cancel = function () {

            $scope.$dismiss();
            //$state.go('root.adv.institutions.instsearch', $scope.reloadData, { reload: true });
            //$state.('root.adv.institutions.summary', { rssd: $scope.criteria.rssdId, isTophold: true });
            $state.go;
        };

        
        activate();

        function activate() {
			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;		}


			//move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                $('[id="rssdId"]')[0].focus();

            }, 750);

            window.scrollTo(0, 0);
            var rssd;
            var NewTopHold;
            var TransactionDate;

            rssd = $state.params.rssd;
            NewTopHold = $state.params.newTopHoldRSSDID;
            TransactionDate = $state.params.TransactionDate;

           
            $scope.ReadyToAcquire = true;
            $scope.Doneacquiring = false;
            genericService.getStates().then(function (result) {
                var criteria = [];
                $scope.criteria = [];
                $scope.states = result;

                //find the criteria that was passed in of the screen that call the form
                //$state.params.reloadData
                $scope.reloadData = $state.params.reloadData;

                AdvInstitutionsService.getEditInstitutionData({ rssdId: rssd }).then(function (result) {
                    if (result && result != null) {
                        //countyFIPSNum
                        var criteria = result;
                        var preCriteria = result;
                        criteria.type = result.type;


                        criteria.state = _.find($scope.states, { stateId: result.stateId });
                        genericService.getCounties(result.stateId).then(function (resultCounty) {
                            criteria.state.counties = resultCounty;

                            criteria.county = _.find(criteria.state.counties, { countyId: result.countyId });

                            var dataCity = {
                                stateId: result.stateId,
                                countyId: result.countyId
                            }
                            genericService.getCities(dataCity).then(function (resultCity) {
                                criteria.county.city = resultCity;
                                criteria.city = _.find(criteria.county.city, { cityId: result.cityId });



                                criteria.InstCategoryId = criteria.entityTypeCode == 'BANK' ? 'B' : 'T';
                                criteria.InstType = criteria.entityTypeCode == 'BANK' ? 'Bank' : 'Thrift';


                                if (NewTopHold != null)
                                {
                                    $scope.pageTitle = "Institution " + criteria.InstType + " Acquired by Tophold";
                                    criteria.newParentRSSDId = NewTopHold;
                                    criteria.historyTransactionDate = TransactionDate;

                                    
                                }
                                else
                                {
                                    if (criteria.parentTopholdRSSDId != criteria.rssdId) {
                                        $scope.pageTitle = "Controlled " + criteria.InstType + " Acquired by Tophold";
                                    }
                                    else {
                                        if (criteria.orgEntityCodeId == 12) {
                                            $scope.pageTitle = "Independent CSA " + criteria.InstType + " Acquired by Tophold";
                                        }
                                        else {
                                            $scope.pageTitle = "Independent " + criteria.InstType + " Acquired by Tophold";
                                        }
                                    }
                                }
                                //if we have a parent RSSDID for the Parent Inst then it is controlled
                                

                        
                                $scope.criteria = criteria;

                                preCriteria = angular.copy(criteria);
                                $scope.preBankCriteria = preCriteria;
                                $scope.criteria.transactionDateType = 2;
                   
                            });
                        });
                    }
                    $scope.institutionLoaded = true;
                });
            }); 

          
        }

       



    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstEditController', AdvInstEditController);

    AdvInstEditController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', 'Dialogger', 'toastr', 'uibDateParser', 'AdvPendingService', '$timeout', 'AdvBranchesService', 'genericService'];


    function AdvInstEditController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, Dialogger, toastr, uibDateParser, AdvPendingService, $timeout, AdvBranchesService, genericService) {
        $scope.txnIds = [];
        $scope.tophold = [];
        $scope.newcitymode = false;
        $scope.THCchanged = false;
        $scope.instData = [];
        $scope.selectRecord = false;
        $scope.pretophold;
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
        $scope.showPendingTransactions = false;
        $scope.contProcessing = true;
        $scope.THCeasesShowDetails = false;
        $scope.THCCeaseLoadData = false;
        $scope.THCCeasesFinishProcessing = false;
        $scope.InstAdded = false;
		$scope.Instchanged = false;
		$scope.deNovoPending = [];
		$scope.showDeNovoPending = false;  
		$scope.pendingReady = true;
		$scope.pendingTransIdToRemove = null; 
		$scope.criteria = [];
		$scope.criteria.packetId = null;
		$scope.criteria.orgEntityTypeCode = null;
		$scope.orgEntityTypes = [];
		$scope.isInstConversion = false;
		$scope.criteria.transactionDateType = 2;


        $scope.switchNewCity = function () {
            $scope.newcitymode = !$scope.newcitymode;
		};

		$scope.loadDeNovoPending = function () {
			if ($scope.recMode == "Add") {
				$scope.pendingReady = false;
				AdvInstitutionsService.getPendingDeNovo($scope.criteria.fdicCert).then(function (results) {
					$scope.pendingReady = true;
					var dat = results.data;
					if (dat && dat.length && dat.length > 0) {
						$scope.deNovoPending = dat;
						$scope.showDeNovoPending = true;
					}
					else {
						$scope.showDeNovoPending = false;
					}
				});
			}
		}

		$scope.setDeNovoPendingTransId = function(pendingTransId) {
			$scope.pendingTransIdToRemove = pendingTransId;
		}

		$scope.clearSelectedDeNovoPending = function () {
			if ($scope.pendingTransIdToRemove == null) {
				toastr.success("No Pending Transactions have been selected!");
			} else {
				$scope.pendingTransIdToRemove = null;
			}			
		};

		$scope.isDeNovoPendingSelected = function (radioPendingTransId) {
			return radioPendingTransId === $scope.pendingTransIdToRemove;
		}

		//$scope.setPendingIdToRemove = function (pendingTransId, isBeingAdded) {
		//	var idx = $scope.pendingTransIdsToRemove.indexOf(pendingTransId);
		//	if (isBeingAdded && idx < 0 ) {
		//		$scope.pendingTransIdsToRemove.push(pendingTransId);
		//	}
		//	else if (!isBeingAdded && idx >= 0) {
		//		var secondPart = $scope.pendingTransIdsToRemove.slice(idx+1);
		//		var firstPart = $scope.pendingTransIdsToRemove.slice(0,idx);
		//		$scope.pendingTransIdsToRemove = firstPart.push(secondPart);
		//	}
		//}

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

            var d = new Date();
            //verify we have transaction date, name, primary 
            if (!$scope.criteria.rssdId) {
                toastr.error("RSSDID is required!");
                $scope.contProcessing = false;
			}

			if (!$scope.criteria.bypassHistory && $rootScope.FeatureToggles.ChangePacketIntegration && (!$scope.criteria.packetId || isNaN($scope.criteria.packetId))) {
				toastr.error("You must select a Firma change record packet!");
				$scope.contProcessing = false;
			}

            if (!$scope.criteria.fdicCert) {
                if ($scope.criteria.fdicCert != 0) {
                    toastr.error("FDIC is required!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.transactionDateType) {
                toastr.error("Transaction Type must be entered!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.name) {
                toastr.error("Name is required!");
                $scope.contProcessing = false;
            }

             
            if (!$scope.criteria.docketNumber && $scope.criteria.InstCategoryId == 'T') {
                if ($scope.criteria.docketNumber != 0)
                {
                    toastr.error("Docket Number is required!");
                    $scope.contProcessing = false;
                }
                   
               
            }

            if (!$scope.criteria.state) {
                toastr.error("State is required!");
                $scope.contProcessing = false;

            }

             if (!$scope.criteria.city) {
                toastr.error("City is required!");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.county) {
                toastr.error("County is required!");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.district) {
                toastr.error("FRS DISTRICT must be between 0 and 12!");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.regulator) {
                toastr.error("Regulator is required");
                $scope.contProcessing = false;

            }

            processchange();

        };

        function processchange() {
            if ($scope.recMode == "Add") {
                if ($scope.contProcessing == true) {
                    //send the new Tophold to the services later
                    // function postInstitution(id, inst) {
                    var instUpdDTO =
                        {
                            RSSDId: $scope.criteria.rssdId,
                            TransactionDate: $scope.criteria.historyTransactionDate,
                            Name: $scope.criteria.name,
                            StateId: $scope.criteria.state.stateId,
                            CountyId: $scope.criteria.county.countyId,
                            CityId: $scope.criteria.city.cityId,
                            Country: $scope.criteria.country,
                            DistrictId: $scope.criteria.district,
                            Docket: $scope.criteria.docketNumber,
                            CharterTypeCode: $scope.criteria.charterTypeCode,
                            Weight: $scope.criteria.hhiWeight,
                            InstitutionRSSDId: $scope.criteria.rssdId,
                            ParentTopholdRSSDId: $scope.criteria.parentTopholdRSSDId,
                            FDICCertNum: $scope.criteria.fdicCert,
                            InstCategoryId: $scope.criteria.InstCategoryId,
                            MSA: $scope.criteria.msa,
                            BankTypeAnalysisCode: $scope.criteria.bankTypeAnalysisCode,
                            Assets: $scope.criteria.assets,
                            CILoans: $scope.criteria.ciLoans,
                            URL: $scope.criteria.url,
                            SDFCodeId: $scope.criteria.sdfCode == null ? null : $scope.criteria.sdfCode.id,
                            SODDate: $scope.criteria.sodDate,
                            LQAssets: $scope.criteria.lqAssets,
                            LQCILoans: $scope.criteria.lqciLoans,
                            LQDeposits: $scope.criteria.lqDeposits,
                            LQDate: $scope.criteria.lqDate,
                            RegulatorId: $scope.criteria.regulator.regulatorId,
							EntityId: $scope.criteria.orgEntityTypeCode ? $scope.criteria.orgEntityTypeCode.entityTypeId : null
                        }


                    var data = {
                        instRecord: instUpdDTO,
                        cascadeToHomeBranch: $scope.criteria.cascadeToHomeBranch,
                        bypassHistory: $scope.criteria.bypassHistory,
                        transDate: $scope.criteria.historyTransactionDate,
						transType: $scope.criteria.transactionDateType,
						firmaPacketId: $scope.criteria.packetId 
                    }

                    processInst(id, data);
                }
            }
        else {
        //this is an edit
                if ($scope.contProcessing == true) {
                    //send the new Tophold to the services later
                    // function postInstitution(id, inst) {
                    var instUpdDTO =
                        {
                                Id: $scope.criteria.id,
                                RSSDId: $scope.criteria.rssdId,
                                TransactionDate: $scope.criteria.historyTransactionDate,
                                Name: $scope.criteria.name,
                                StateId: $scope.criteria.state.stateId,
                                CountyId: $scope.criteria.county.countyId,
                                CityId: $scope.criteria.city.cityId,
                                Country: $scope.criteria.country,
                                DistrictId: $scope.criteria.district,
                                Docket: $scope.criteria.docketNumber,
                                CharterTypeCode: $scope.criteria.charterTypeCode,
                                Weight: $scope.criteria.hhiWeight,
                                InstitutionRSSDId: $scope.criteria.rssdId,
                                ParentTopholdRSSDId: $scope.criteria.parentTopholdRSSDId,
                                FDICCertNum: $scope.criteria.fdicCert,
                                InstCategoryId: $scope.criteria.InstCategoryId,
                                MSA: $scope.criteria.msa,
                                BankTypeAnalysisCode: $scope.criteria.bankTypeAnalysisCode,
                                Assets: $scope.criteria.assets,
                                CILoans: $scope.criteria.ciLoans,
                                URL: $scope.criteria.url,
                                SDFCodeId: $scope.criteria.sdfCode.id,
                                SODDate: $scope.criteria.sodDate,
                                LQAssets: $scope.criteria.lqAssets,
                                LQCILoans: $scope.criteria.lqciLoans,
                                LQDeposits: $scope.criteria.lqDeposits,
								LQDate: $scope.criteria.lqDate,
								EntityId: $scope.criteria.orgEntityTypeCode ? $scope.criteria.orgEntityTypeCode.entityTypeId : null,
								//EntityId: $scope.criteria.orgEntityCodeId
                                RegulatorId: $scope.criteria.regulator.regulatorId
                            //ParentTopholdRSSDId: $scope.criteria.ParentTopholdRSSDId
                }

                    var id = $scope.criteria.id;

                    var data = {
                            instRecord: instUpdDTO,
                            cascadeToHomeBranch: $scope.criteria.cascadeToHomeBranch,
                            bypassHistory: $scope.criteria.bypassHistory,
                            transDate: $scope.criteria.historyTransactionDate,
							transType: $scope.criteria.transactionDateType,
							firmaPacketId: $scope.criteria.packetId 
                }

                    processInst(id, data);

    }
            }
        }


        function processInst(id, data) {

            if ($scope.recMode == 'Closed')
            {
                var confirmDialog = Dialogger
                .confirm("Are you sure you want to delete " + $scope.criteria.name + "?", null, true);
                confirmDialog.then(function (confirmed) {
                if (confirmed) 
                {
                  AdvInstitutionsService.postcloseInstitution(data).then(function(results) {
                        window.scrollTo(0, 0);
                        if (results.errorFlag == false)
                            {
                                $scope.InstAdded = false;
                                $scope.Instchanged = false;
                                $scope.instDataReady = false;
                                $scope.InstShowdetails = false;
                                $scope.InstClosed = true;
                        }
                        else
                            {
                                //var errorMessage = [];
                                if (results.messageTextItems.length > 0) {
                                for (var i = 0; i < results.messageTextItems.length; i++) {
                                toastr.error(results.messageTextItems[i]);
                            }
                        }
                     }
                            }, function (err) {
                        alert("Sorry. There was an error.");
                        });
                }
                });
                }
                else
                {
             AdvInstitutionsService.postInstitution(id, data).then(function (results) {
                window.scrollTo(0, 0);
                if (results.errorFlag == false)
                {
                    $scope.InstAdded = true;
                    $scope.THCData = false;
                    if (id)
                    {
                        $scope.InstAdded = false;
                        $scope.Instchanged = true;
                        $scope.instDataReady = false;
                        $scope.InstShowdetails = false;
                        toastr.success("Institution was updated");
                        window.scrollTo(0, 0);
					}
                    else
					{
						if ($scope.pendingTransIdToRemove != null && !isNaN($scope.pendingTransIdToRemove)) {
							AdvPendingService.getDeletedTransactions($scope.pendingTransIdToRemove).then(function (result) {
								if (!result || (result.pendingLoaded && result.pendingLoaded === true)) {
									toastr.error("Error deleting pending transaction");
								}
								else {
									$scope.showDeNovoPending = false;
								}
							});
						}
						$scope.InstAdded = true;
                        $scope.Instchanged = false;
                        $scope.instDataReady = false;
                        $scope.InstShowdetails = false;
                        toastr.success("Institution was created");
                        window.scrollTo(0, 0);
                    }

                 }
                 else {
                    //var errorMessage = [];
                    if (results.messageTextItems.length > 0) {
                        for (var i = 0; i < results.messageTextItems.length; i++) {
                            toastr.error(results.messageTextItems[i]);
                    }
                }

             }
             }, function (err) {
                alert("Sorry. There was an error.");
        });
            }
           

        }


        $scope.maxLengthCheck = function (object) {
            if (object.value.length > object.maxLength)
                object.value = object.value.slice(0, object.maxLength)
        };

        $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /[0-9]|\./;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
            }
        };


        $scope.updateCatType = function ()
        {
            //display the confirmation screen and make sure they want to do this?
            
                    if ($scope.criteria.InstCategoryId == 'B') {
                        $scope.criteria.hhiWeight = '1';
                        $scope.criteria.charterTypeCode = '200';
                        $scope.criteria.cascadeToHomeBranch = false;
                        //using the pagetile to tell if we are in edit mode or add mode
                        //if ($scope.recMode != 'Edit')
                        //{
                        //    $scope.pageTitle = 'Bank Charter';
                        //    $scope.recMode = 'Add';
                        //    $state.params.mode == 'AddBank'
                        //}
                        
                        
                    }
                    else {
                        //else thrift weight .5  charter - 300
                        $scope.criteria.hhiWeight = '.5';
                        $scope.criteria.charterTypeCode = '300';
                        //if ($scope.recMode != 'Edit') {
                        //    $scope.pageTitle = 'Thrift Charter';
                        //    $scope.recMode = 'Add';
                        //    $state.params.mode == 'AddThrift'
                        //}
                    }
                    AdvInstitutionsService.getSDFCodes($scope.criteria.InstCategoryId).then(function (data) {
                        $scope.sdfCodes = data;

                    });


            
        }

        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
			popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        // this is hacky, replace with better solution
        $scope.showCancel = function () {

            return !$rootScope.isInWizard && $scope.$dismiss != null;

        };


        $scope.cancel = function () {

            $scope.$dismiss();
            //$state.('root.adv.institutions.summary', { rssd: $scope.criteria.rssdId, isTophold: true });
            $state.reload();
        };


        $scope.toggle = function (id, rssdid, memo) {
            $scope.txnIds = [];
            $scope.txnIds.push(id);

            $scope.criteria.pendingtransactionRSSDID = rssdid;
            $scope.criteria.pendingtransactionmemo = memo;
        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };

        $scope.getMSAList = function () {

        var data = {
                        districtId: $scope.criteria.district,
                        stateId: $scope.criteria.state.stateId,
                        countyId: $scope.criteria.county.countyId,
                    }

            AdvInstitutionsService.getmsabyDistrictID(data).then(function (results) 
            {
                if (results.msaId != 0)
                    $scope.criteria.msa = results.msaId;
                    
                else
                    $scope.criteria.msaId = 0;
                
                    
            });
             
        };

       

        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = [];
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

        $scope.getRSSDID = function () {
            var data =
            {
                SurvivorRssdId: $scope.criteria.rssdId
            }
            AdvPendingService.getPendingTopholds(data).then(function (result) {
                if (result.pending.length > 0) {
                    $scope.criteria.rssdidStatusMessage = result.errorMessage;
                    $scope.tophold = result.pending;
                    $scope.pendingReady = true;
                }
                else {
                    $scope.pendingReady = false;
                    $scope.criteria.rssdidStatusMessage = result.errorMessage;
                }
                $scope.pending = true;
            });


        };

        $scope.populateWeight = function()
        {
            //if the sdf was change to MISC then we need to make the weight and charter type code editable
            if ($scope.criteria.sdfCode.name == 'MISC')
            {
                $scope.sdfeditable = true;
            }
            else
            {
                $scope.sdfeditable = false;
            }


            //if the tophold is a bank
            if ($scope.criteria.sdfCode.name == 'NONE' || $scope.criteria.sdfCode.name == 'CO-OP' )
            {
                if($scope.criteria.InstCategoryId == 'B')
                {
                    $scope.criteria.hhiWeight = 1;
                    $scope.criteria.charterTypeCode = '200';
                }
                else
                {
                    $scope.criteria.hhiWeight = 0.5;
                }
                
            }
            else
            {
                //set to default
                $scope.criteria.hhiWeight = 0;
                if($scope.criteria.InstCategoryId == 'B')
                {
                    
                    $scope.criteria.charterTypeCode = '200';
                }
                else
                {
                    $scope.criteria.charterTypeCode = '300';
                }

            }

            if ($scope.criteria.sdfCode.name == 'ILC')
            {
                $scope.criteria.charterTypeCode = '340';
            }

            if ($scope.criteria.sdfCode.name == 'CO-OP')
            {
                $scope.criteria.charterTypeCode = '320';
            }

        }



        $scope.populateDistrictID = function () {
            var data =
            {
                stateFipsId: $scope.criteria.state.stateId,
                countyId: $scope.criteria.county.countyId
            }


            AdvInstitutionsService.getDistrictByLocation(data).then(function (data) {
                if (data.errorFlag == false) {
                    //now update the  instUpdDTO object
                    $scope.criteria.district = data.districtId;
                    $scope.getMSAList();
                }
                else {
                    //there was an error toast and exit
                    $scope.criteria.district = 0;
                }
            }, function (err) {
                alert("Sorry. There was an error.");
            });


            var data =
            {
                stateId: $scope.criteria.state.stateId,
                countyId: $scope.criteria.county.countyId
            }

            //populate the city from the county and state dropdown
            genericService.getCities(data).then(function (result) {
                $scope.criteria.county.city = result;
            });


        };



        activate();

        $scope.UpdateCounties = function () {
            $scope.criteria.city = null;
            $scope.criteria.county = null;

            genericService.getCounties($scope.criteria.state.stateId).then(function (result) {
                $scope.criteria.state.counties = result;
            });

           


        }
        $scope.changeEntityType = function () {
            var data = $scope.criteria.orgEntityTypeCode;
            var type = $scope.criteria.TypeCode;

            if (data.entityTypeId == 12) {
                $scope.criteria.hhiWeight = "1.0";
            }
            else {
                if (type.toLowerCase() == "thrift") {
                    $scope.criteria.hhiWeight = "0.5";
                }
            }
        };
        function activate() {
			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}


			//move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                $('[id="historyTransactionDate _input"]')[0].focus();

            }, 750);

            window.scrollTo(0, 0);

            $scope.InstShowdetails = true;

            $scope.sdfeditable = false;

            AdvInstitutionsService.getRegulators().then(function (result) {
                $scope.regulators = result;
            });

			AdvInstitutionsService.getOrgEntityTypeCodes().then(function (data) {
				$scope.orgEntityTypes = data;
			});

            //StatesService.statesPromise.then(function (result) {
            genericService.getStates().then(function (result) {
                var criteria = [];
                $scope.criteria = [];
                $scope.states = result;
                $scope.statesLoaded = true;
                $scope.instDataReady = true;
                $scope.showHistoryOption = true;
                var rssd;
                var parentTopHoldRSSD;
                //$state.params.mode = mode;
                //$state.params.parentRSSD = parentRSSD;
                // This is very hacky.  We need to find a better way of communicating the caller's intention
                if ($scope.$parent.$parent == null ) {

                    if ($scope.criteria) {
                        rssd = $scope.criteria.rssdId ? $scope.criteria.rssdId : $state.params.rssd;
                        parentTopHoldRSSD = $state.params.parentRSSD;
                    }
                    else {
                        rssd = $state.params.RSSDId ? $state.params.RSSDId : $state.params.rssd;
                        parentTopHoldRSSD = $state.params.parentRSSD;

                    }
                }
                else
                {
                    rssd = $scope.criteria.rssdId ? $scope.criteria.rssdId : $state.params.rssd;
                }

                

                //if (rssd == null || rssd == '') {
                if ($state.params.mode == 'AddBank' || $state.params.mode == 'AddThrift')
                {

                    if ($state.params.mode == 'B' || $state.params.mode == 'AddBank')
                    {
                        $scope.criteria.InstCategoryId = 'B';
                    }
                    else if  ($state.params.mode == 'T' || $state.params.mode == 'AddThrift')
                    {
                        $scope.criteria.InstCategoryId = 'T';
                    }
                     else
                    {
                        return;
                    }
                    //need to move this to a method so we can call this later
                    AdvInstitutionsService.getSDFCodes($scope.criteria.InstCategoryId).then(function (data) {
                        $scope.sdfCodes = data;
                        //$scope.criteria.sdfCode = $scope.sdfCodes;
                        $scope.criteria.sdfCode = _.find($scope.sdfCodes, { name: 'NONE' });
                        $scope.recMode = "Add";
                        $scope.pageTitle = $scope.criteria.InstCategoryId == 'B' ? 'Bank Charter' : 'Thrift Charter';
                        $scope.runDate = new Date();
                        $scope.criteria.transactionDateType = 2;
                        $scope.criteria.bypassHistory = false;
                        $scope.runDate = new Date();
                        $scope.showHistoryOption = false;
                        //$scope.criteria.parentTopholdRSSDId = parentTopHoldRSSD;
                        $scope.criteria.rssdId = rssd;
                        
                        $scope.criteria.assets = '0.000';
                        $scope.criteria.ciLoans =  '0.000';
                        $scope.criteria.lqDeposits =  '0.000';
                        $scope.criteria.country = 'USA';
                        $scope.criteria.sodDate = "06/30/2023";

                        if ($scope.criteria.InstCategoryId == 'B')
                        {
                            $scope.criteria.hhiWeight = '1';
                            $scope.criteria.charterTypeCode = '200';
                        }
                        else
                        {
                                //else thrift weight .5  charter - 300
                            $scope.criteria.hhiWeight = '.5';
                            $scope.criteria.charterTypeCode = '300';
                        }
                    });
                }
                else {
                    AdvInstitutionsService.getEditInstitutionData({ rssdId: rssd }).then(function (result) {
                        if (result && result != null) {
                            //countyFIPSNum
                            var criteria = result;
							var preCriteria = result;

							$scope.linkOrgEntityCodeToInst(criteria, criteria.orgEntityCodeId);

                            criteria.InstCategoryId = criteria.entityTypeCode == 'BANK' ? 'B' : 'T';
                            criteria.TypeCode = criteria.entityTypeCode == 'BANK' ? 'Bank' : 'Thrift';
                            criteria.newEntityTypeCode = criteria.entityTypeCode == 'BANK' ? 'Thrift' : 'Bank';	
                            
                            criteria.type = result.type;
                            criteria.state = _.find($scope.states, { stateId: result.stateId });
                            criteria.regulator = _.find($scope.regulators, { regulatorId: result.regulatorId });
                            genericService.getCounties(result.stateId).then(function (resultCounty) {
                                criteria.state.counties = resultCounty;

                                criteria.county = _.find(criteria.state.counties, { countyId: result.countyId });

                                var dataCity = {
                                    stateId: result.stateId,
                                    countyId: result.countyId
                                }
                                genericService.getCities(dataCity).then(function (resultCity) {
                                    criteria.county.city = resultCity;
                                    criteria.city = _.find(criteria.county.city, { cityId: result.cityId });


                               
                                //need to move this to a method so we can call this later
                                AdvInstitutionsService.getSDFCodes(criteria.InstCategoryId).then(function (data) {
                                    $scope.sdfCodes = data;

                                    criteria.sdfCode = _.find($scope.sdfCodes, { name: result.sdf });

                                    $scope.criteria.bypassHistory = false;


                                    $scope.instDataReady = true;
                                    $scope.criteria = criteria;

                                    preCriteria = angular.copy(criteria);
                                    $scope.preInst = preCriteria;
                                    if ($state.params.mode == 'closedInst') {
                                        $scope.pageTitle = criteria.TypeCode + " Closed";
                                        $scope.recMode = 'Closed';
                                        $scope.sdfeditable = false;
                                        $scope.showHistoryOption = false;
                                        $scope.readonlydetails = true;
                                        $scope.preInst.cascadeToHomeBranch = true;
                                    }
                                        //so we are in edit mode but we can be in attr update mode or convert mode
									else if ($state.params.mode == "convertInst") {										
                                        $scope.pageTitle = criteria.TypeCode + " Converts to " + criteria.newEntityTypeCode;
										criteria.name = '';
										$scope.isInstConversion = true;
                                        $scope.recMode = 'Convert';
                                        $scope.sdfeditable = false;
                                        $scope.showHistoryOption = false;
                                        $scope.readonlydetails = true;
                                        $scope.preInst.cascadeToHomeBranch = true;
                                        //default the 
                                        if (criteria.InstCategoryId == 'B') {
                                            if (criteria.parentTopholdRSSDId == criteria.rssdId) {
                                                criteria.hhiWeight = '.5';
                                                criteria.InstCategoryId = 'T';
                                                criteria.charterTypeCode = '300';
                                            }
                                            else {
                                                //we need to check to see if the TH is a Thrift.  If it a SLHC should be .5 if BHC then a 1
                                                AdvInstitutionsService.getEditTopholdData({ rssdId: criteria.parentTopholdRSSDId }).then(function (THresult) {
                                                    if (THresult.entityTypeCode == 'SLHC' || THresult.entityTypeCode == 'THC') {
                                                        criteria.hhiWeight = '.5';                                                        
                                                    }
                                                    else {
                                                        criteria.hhiWeight = '1';
                                                    }
                                                    criteria.InstCategoryId = 'T';
                                                    criteria.charterTypeCode = '300';

                                                });
                                            }


                                        }
										else {
											AdvInstitutionsService.getEditTopholdData({ rssdId: criteria.parentTopholdRSSDId }).then(function (THresult) {
												if (THresult.entityTypeCode == 'SLHC' || THresult.entityTypeCode == 'THC') {
													Dialogger.alert('You cannot convert a Thrift to a Bank under an SLHC! You must first convert the SLHC to a BHC.').then(function (result) {
														toastr.error('You cannot convert a Thrift to a Bank under an SLHC!');
														$scope.$dismiss();
														$state.reload();
													});
												}
											});

                                            criteria.InstCategoryId = 'B';
                                            criteria.hhiWeight = '1';
                                            criteria.charterTypeCode = '200';
                                        }



                                    }
                                    else {
                                        $scope.pageTitle = "Attribute Update";
                                        $scope.recMode = "Edit";
                                        $scope.readonlydetails = false;
                                        if (criteria.entityTypeCode == 'BANK') {
                                            for (var i = 0; i < $scope.orgEntityTypes.length; i++) {
                                                if ($scope.orgEntityTypes[i].entityTypeId == 12) {
                                                    $scope.orgEntityTypes.splice(i, 1);
                                                }
                                            }
                                           // $scope.criteria.orgEntityTypeCode = $scope.orgEntityTypes;
                                        }
                                    }

                                    $scope.InstAdded = false;
                                    $scope.Instchanged = false;
                                    $scope.criteria.transactionDateType = 2;
                                    $scope.instDataReady = true;
                                });
                                });								
                            });

                            
                            

                        }
                        $scope.institutionLoaded = true;
                    });
                }
			});		

        }

         $scope.updateHomeBranch = function () 
        {
            $scope.criteria.cascadeToHomeBranch=true;
        };

         $scope.openEditBranchForm = function (BankRSSDID, criteria, mode) {
             //set the state params so we can use thru out app
             $state.params.mode = mode;
             $state.params.BankRSSDID = BankRSSDID;
             $state.params.Bankcriteria = criteria;

             AdvInstitutionsService.addOrEditBranch(null);


         };

        $scope.openAcquireByTophold = function (BankRSSDID, criteria, mode) {
             //set the state params so we can use thru out app
             $state.params.mode = mode;
             $state.params.BankRSSDID = BankRSSDID;
             $state.params.Bankcriteria = criteria;

             AdvInstitutionsService.addOrEditBranch(null);


		};

		$scope.linkOrgEntityCodeToInst = function (objCriteria, entCodeId) {
			objCriteria.orgEntityTypeCode = _.find($scope.orgEntityTypes, { entityTypeId: entCodeId});
		}


        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.institutions";
        };    

    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionBankFailureController', AdvInstitutionBankFailureController);

    AdvInstitutionBankFailureController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', '$uibModal', 'toastr', 'uibDateParser', '$timeout', 'AdvBranchesService', 'AdvMarketsService', 'Dialogger'];

    function AdvInstitutionBankFailureController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, $uibModal, toastr, uibDateParser, $timeout, AdvBranchesService, AdvMarketsService, Dialogger) {

        $scope.instData = [];
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
        $scope.criteria = {};
        $scope.nonSuvivorList = [];
        $scope.NonSuvivorListPrintInfo = {};
        $scope.adjusted = false;
        $scope.adjDeposits = 0;
        $scope.adjAssets = 0;
		$scope.depositsLoading = false;
		$scope.working = false;
		$scope.criteria.packetId = null;

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

            var d = new Date();


            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }
            if ($scope.contProcessing) {

                processrequestFailedInstMergeIntoInst();

            }
        };

        $scope.populateDepositsAssets = function () {            

            if ($scope.criteria.nonSurvRSSD) {
                var instobj = {
                    rssdIdList: $scope.criteria.nonSurvRSSD
                }

                $scope.depositsLoading = true;
                AdvInstitutionsService.getInstitutionListForMulRSSDID(instobj).then(function (result) {
                    if (result && result != null) {
                        if (!result.errorFlag) {
                            //should only be one
                            $scope.NonSuvivorListPrintInfo = result.instList;
                            $scope.nonSuvivorList =[];
                            //now loop thru the nonsuvlist returned and populate the smaller object/the nonsurlist will be used for printing
                            angular.forEach($scope.NonSuvivorListPrintInfo, function (value, key) {
                                var NonSuvivor = { InstitutionId: value.definition.id, RSSDID: value.definition.rssdId, AdjustedDeposits: value.definition.totalBranchDeposits, AdjustedAssets: value.definition.assets };
                                $scope.nonSuvivorList.push(NonSuvivor);
                            });
                        }
                    }

                    $scope.depositsLoading = false;
                });
            }
        }

        $scope.populateSurvivorInfo = function () {
            AdvInstitutionsService
                          .getInstitutionData({ rssdId: $scope.criteria.SurvRSSD, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                          .then(function (result) {
							  if (result && result != null && result.definition) {
								  $scope.survivingrssd = result.definition;
								  $scope.SurvInstType = $scope.survivingrssd.class == 'BANK' ? 'Bank' : 'Thrift';
							  }
							  else {
								  $scope.survivingrssd = {};
							  }
                          });
		}

		$scope.adjust = function (adjOrg) {
			var origOrgData = _.find($scope.NonSuvivorListPrintInfo, function (n) { return n.definition.rssdId && n.definition.rssdId === adjOrg.RSSDID });
			if (origOrgData && origOrgData.definition) {
				if (origOrgData.definition.assets !== adjOrg.AdjustedAssets || origOrgData.definition.totalBranchDeposits !== adjOrg.AdjustedDeposits) {
					$scope.adjusted = true;
				}
			}
		}

        $scope.displayTotals = function () {
            var nonsurv = 0;
            var surv = 0;

            //check to see if we adjusted
            if ($scope.adjusted == true)
            {
                nonsurv = parseFloat($scope.nonSuvivorList[0].AdjustedDeposits);
                $scope.adjDeposits = parseFloat($scope.nonSuvivorList[0].AdjustedDeposits);
                $scope.adjAssets = $scope.nonSuvivorList[0].AdjustedAssets;
            }
            else
            {
                    if ($scope.NonSuvivorListPrintInfo) {
                        angular.forEach($scope.NonSuvivorListPrintInfo, function (value, index) {
                            nonsurv = nonsurv + value.definition.totalBranchDeposits
                        })
                    }
            }
            


            if ($scope.survivingrssd) {
                surv = $scope.survivingrssd.totalBranchDeposits;
            }
            return parseFloat(nonsurv) + surv;
        }


        $scope.gotoBranchList = function () {
            $state.go('root.adv.institutions.summary.orgs', { rssd: $scope.survivingrssd.rssdId });
            $scope.$dismiss();
        }

        $scope.gotoBranchSearchList = function () {
            $state.go('root.adv.institutions.branchreport');
            $scope.$dismiss();
        }

        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        function processrequestFailedInstMergeIntoInst() {
			$scope.working = true;

            //var nonSurvivorList = [];
            var nonSurvivorList = $scope.criteria.nonSurvRSSD.toString().split(',');
            var nonSuvivorAdjList = [];	

            //for the print confirmation we need to load the inst that we just entered in
            //look up the inst details 
            //need to look this up before the merge
            var instobj = {
                rssdIdList: $scope.criteria.nonSurvRSSD
            }
            AdvInstitutionsService.getInstitutionListForMulRSSDID(instobj).then(function (result) {				
				if (result && result != null) {
                    if (!result.errorFlag) {
                        $scope.nonrssdid = result.instList;
                    }
                }
            });

            //we need to loop thru the array and then populate it into the nonsurvAdj
            angular.forEach($scope.nonSuvivorList, function (value, key) {

                var nonSurvAdj = {
                    InstitutionId: value.InstitutionId,
                    AdjustedAssets: value.AdjustedAssets,
                    AdjustedDeposits: value.AdjustedDeposits
                }

                nonSuvivorAdjList.push(nonSurvAdj);
            });

            var instMegeIntoinstInfo = {
                nonSurvivorRssdID: nonSurvivorList,
                nonSurvivoradj: nonSuvivorAdjList,
                survivorRssdID: $scope.survivingrssd.rssdId,
                transDate: $scope.criteria.historyTransactionDate,
				transType: 2,
				firmaPacketId: $scope.criteria.packetId
            }

            AdvInstitutionsService.postInsFailedtMergeIntoInst(instMegeIntoinstInfo)
				.then(function (result) {
					$scope.working = false;
					 if (!result.errorFlag) {
						 $scope.displayConfirmation = true;
						 $scope.instDataReady = false;
						 $scope.Instchanged = true;

						 toastr.info("Success: " + $scope.InstType + " Failed");


					 }
					 else {

						 if (result.messageTextItems.length > 0) {
							 for (var i = 0; i < result.messageTextItems.length; i++) {
								 toastr.error(result.messageTextItems[i]);
							 }
						 }

					 }
				});
        }

        $scope.cancel = function () {
            $scope.$dismiss();
            $state.reload();
        };


        activate();

        function activate() {
			var rssd = 0;

			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}

            //move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                var focusField = $('[id="historyTransactionDate"]');
                if (focusField && focusField.length > 0 && focusField[0].focus) {
                    $('[id="historyTransactionDate"]')[0].focus();
                }

            }, 750);

            window.scrollTo(0, 0);


            //set the nonSurvRSSDID
            $scope.criteria.nonSurvRSSD = '';

            //we need to populate the screen
             if ($state.params.MergedRSSDID)
            {
                rssd = $state.params.MergedRSSDID;
            }
            else
            {
                rssd = $state.params.rssd;
            }

            $scope.criteria.nonSurvRSSD = rssd;

            AdvInstitutionsService
            .getInstitutionData({
                    rssdId: rssd, getDetail : true, getBranches: false, getOperatingMarkets: false, getHistory : false
            })
                .then(function (result) {
                    if (result && result != null) {
                        $scope.nonsurvivingrssd = result.definition;
                        $scope.InstType = $scope.nonsurvivingrssd.class == 'BANK' ? 'Bank' : 'Thrift';
                        $scope.populateDepositsAssets();
                        if ($state.params.mode == 'failedMergeintoBank') {
                            $scope.pageTitle = $scope.InstType + " Failure into Existing " + $scope.SurvInstType;
                            $scope.mode = $state.params.mode;
                            $scope.surviveMode = 'Bank';
                            $scope.nonsurviveMode = 'Bank';
                        }
                        else if ($state.params.mode == 'failedMergeintoThrift') {
                            $scope.pageTitle = $scope.InstType + " Failure into Existing " + $scope.SurvInstType;
                            $scope.mode = $state.params.mode;
                            $scope.surviveMode = 'Bank';
                            $scope.nonsurviveMode = 'Thrift';
                        }

                    }
                });



            //populated the screen correctly
            $scope.instDataReady = true;
            $scope.Instchanged = false;














        }

    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionBrowseCountiesController', AdvInstitutionBrowseCountiesController);

    AdvInstitutionBrowseCountiesController.$inject = ['$scope', '$state', '$stateParams', 'StatesService'];

    function AdvInstitutionBrowseCountiesController($scope, $state, $stateParams, StatesService) {
        if (!$stateParams.state) {
            $state.go("^");
            return;
        }

        $scope.hasState = true;
        $scope.stateName = $stateParams.state;
        $scope.stateId = 0;
        $scope.counties = [];
        $scope.countiesReady = false;

        activate();

        function activate() {
            StatesService.statesPromise.then(function (result) {
                var states = result,
                    state = _.find(states, { state: $stateParams.state });

                $scope.stateId = state.stateId;
                $scope.counties = state.counties;
                $scope.countiesReady = true;
            });
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsBranchAreaListController', AdvInstitutionsBranchAreaListController);

    AdvInstitutionsBranchAreaListController.$inject = ['$scope', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants'];

    function AdvInstitutionsBranchAreaListController($scope, $stateParams, $timeout, $templateCache, AdvInstitutionsService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants) {
        $scope.instData = [];
        $scope.instDataReady = false;

        $scope.totalInstItems = 0;
        $scope.instItemsPerPage = 50;
        $scope.currentInstPage = 1;
        $scope.instPageCount = function () {
            return Math.ceil($scope.instData.length / $scope.instItemsPerPage);
        };

        // Need to get user friendly names from Ids
        $scope.state = $stateParams.state;
        $scope.city = $stateParams.city,
        $scope.county = $stateParams.county;
        $scope.zip = $stateParams.zip;
        $scope.marketNumber = $stateParams.marketNumber;
        $scope.customMarket = $stateParams.customMarket;


        activate();

        function activate() {
            var params = {
                marketNumber: $scope.marketNumber,
                state: $scope.criteria.state ? $scope.criteria.state.stateId : null,
                county: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                city: $scope.criteria.city ? $scope.criteria.city.cityId : null,
                zip: $scope.criteria.zip,
                customMarket: $scope.customMarket
            };
            AdvInstitutionsService.getBranchSearchData(params).then(function (result) {
                $scope.instData = result;
                $scope.instDataReady = true;
                $scope.todaysDate = new Date();
                var branchCount = 0;
                var totalDeposits = 0;
                for (var i = 0; i < $scope.instData.length; i++) {
                    branchCount += $scope.instData[i].branches.length;
                    for (var j = 0; j < $scope.instData[i].branches.length; j++) {
                        totalDeposits += $scope.instData[i].branches[j].deposits;
                    }

                }
                $scope.branchCount = branchCount;
                $scope.totalDeposits = totalDeposits;
                $scope.searchCriteria = [];
                if ($scope.city != null) {
                    $scope.searchCriteria.push($scope.instData[0].city);
                }
                if ($scope.county != null) {
                    $scope.searchCriteria.push($scope.instData[0].county);
                }
                if ($scope.state != null) {
                    $scope.searchCriteria.push($scope.instData[0].stateCode);
                }
                if ($scope.marketNumber != null) {
                    $scope.searchCriteria.push("Market " + $scope.marketNumber);
                }
                if ($scope.customMarket != null) {
                    $scope.searchCriteria.push("Custom Market " + $scope.customMarket);

                }
                if ($scope.zip != null) {
                    $scope.searchCriteria.push($scope.zip);

                }
                $scope.searchCriteriaStr = $scope.searchCriteria.join();
            });
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsBranchReportController', AdvInstitutionsBranchReportController);

    AdvInstitutionsBranchReportController.$inject = ['$scope', '$rootScope', '$stateParams', 'AdvInstitutionsService', '$uibModal', 'toastr', 'uibDateParser', 'AdvBranchesService'];

    function AdvInstitutionsBranchReportController($scope, $rootScope, $stateParams, AdvInstitutionsService, $uibModal, toastr, uibDateParser, AdvBranchesService) {

        $scope.totalInstItems = 0;
        $scope.instItemsPerPage = 50;
        $scope.currentInstPage = 1;
        $scope.instPageCount = function () {
            return Math.ceil($scope.instData.length / $scope.instItemsPerPage);
        };

        // Need to get user friendly names from Ids
        $scope.branchId = $stateParams.branchId;

       

     

        activate();

        function activate() {

            var params = {
                branchId: $scope.branchId
            };
            AdvBranchesService.getBranchDetail(params).then(function (result) {

                $scope.instData = result;
                $scope.instDataReady = true;
                $scope.instReportDataReady = true;





            });
        }
    }
})();
;


(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvInstitutionsBranchSearchController', AdvInstitutionsBranchSearchController);

    AdvInstitutionsBranchSearchController.$inject = [
        '$scope', '$state', 'AdvBranchesService', 'StatesService', '$window', '$stateParams', '$timeout', '$http', '$sce',
    ];

    function AdvInstitutionsBranchSearchController($scope,
        $state,
        AdvBranchesService,
        StatesService,
        $window,
        $stateParams,
        $timeout,
        $http,
        $sce) {

        $scope.scrollLoadDefaultCount = 10;
        $scope.scrollLoadBatchSize = 1;
        $scope.scrollLoadCount = $scope.scrollLoadDefaultCount;
        $scope.totalInstCount = 0;
        $scope.showMoreLinkVisible = false;

        $scope.branchCriteria = [];
        $scope.hiddeCriteria = false;

        $scope.criteriaEntered = function() {
            return $scope.branchCriteria.rssdId != null ||
                $scope.branchCriteria.fdicId != null ||
                $scope.branchCriteria.city != null ||
                $scope.branchCriteria.name != null ||
                $scope.branchCriteria.marketNumber != null ||
                $scope.branchCriteria.state != null ||
                $scope.branchCriteria.county != null ||
                $scope.branchCriteria.zip != null ||
                $scope.branchCriteria.sdfCode != null ||
				$scope.branchCriteria.customMarket != null ||
				$scope.branchCriteria.districtId != null
				
        };

        $scope.displayCriteria = function (value) {
            $scope.hiddeCriteria = !value;

        };

        $scope.clearCriteria = function () {
            $scope.branchCriteria.rssdId = null;
            $scope.branchCriteria.fdicId = null;
            $scope.branchCriteria.fdisId = null;
            $scope.branchCriteria.city = null;
            $scope.branchCriteria.name = null;
            $scope.branchCriteria.marketNumber = null;
            $scope.branchCriteria.state = null;
            $scope.branchCriteria.county = null;
            $scope.branchCriteria.zip = null;
            $scope.branchCriteria.sdfCode = null;
			$scope.branchCriteria.customMarket = null;
			$scope.branchCriteria.districtId = null;
            $scope.searchState = 'initial';
        };

        $scope.resetLoadMoreCounter = function () { $scope.scrollLoadCount = $scope.scrollLoadDefaultCount; };

        $scope.loadMoreOnWindowScroll = function (ignoreWindowPosition) {
            $scope.$apply(function () {
                if (($scope.scrollLoadCount < $scope.totalInstCount) && ($(window).scrollTop() > $(document).height() - $(window).height() - 225)) {
                    $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                    $scope.searchState = 'scrollLoading'; 
                }
            });
        }

        $scope.loadMoreOnLinkClick = function () {
            if ($scope.scrollLoadCount < $scope.totalInstCount) {
                $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                $scope.searchState = 'scrollLoading';
            }
        }

        $scope.onLoadMoreComplete = function () {
            $scope.clearLoadingMoreMsg();
        }

        $scope.clearLoadingMoreMsg = function () {
            $timeout(function () { $scope.searchState = 'loaded'; }, 3000);
        }

        activate();

        function activate() {
            var data = {
                includeDC: true,
                includeTerritories: true
            };
            StatesService.getStateSummaries(data).then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
            angular.element($window).on('scroll', $scope.loadMoreOnWindowScroll);
            $scope.$on('$destroy', function () {
                angular.element($window).off('scroll', $scope.loadMoreOnWindowScroll);
            });
            $scope.hideReportLoading = true;
        }

        $scope.UpdateCountysAndCitys = function () {
            $scope.criteria.city = null;
            $scope.criteria.county = null;

            var data = {stateFIPSId: null};
            if ($scope.branchCriteria.state) {
                data = {stateFIPSId: $scope.branchCriteria.state.fipsId};

                StatesService.getCityNames(data).then(function (result) {
                    $scope.branchCriteria.state.cities = result;
                });

                StatesService.getCountySummaries(data).then(function (result) {
                    $scope.branchCriteria.state.counties = result;
                });
            }           
        }

        $scope.SearchOrgSubmit = function() {

            $scope.resetLoadMoreCounter();

            //if ($scope.branchCriteria.rssdId)
            //{
            //    $state.go('root.adv.institutions.summary.orgs', { rssd: $scope.branchCriteria.rssdId });
            //}

            $scope.todaysDate = new Date();

            var cityName = '';
            if ($scope.branchCriteria.internationalCity != null) {
                cityName = $scope.branchCriteria.internationalCity.name;
            } else {
                cityName = $scope.branchCriteria.city ? $scope.branchCriteria.city.name : null;
            }


            var data = {
                name: $scope.branchCriteria.name,
                marketNumber: $scope.branchCriteria.marketNumber,
                state: $scope.branchCriteria.state ? $scope.branchCriteria.state.fipsId : null,
                county: $scope.branchCriteria.county ? $scope.branchCriteria.county.countyId : null,
                cityName: cityName,
                zip: $scope.branchCriteria.zip,
                sdfCodeId: $scope.branchCriteria.sdfCode,
                customMarket: $scope.branchCriteria.customMarket ? $scope.branchCriteria.customMarket.marketId : null,
                parentRssdId: $scope.branchCriteria.rssdId,
				fdicId: $scope.branchCriteria.fdicId,
				districtId: $scope.branchCriteria.districtId
            };

            $scope.searchState = 'loading';
            $scope.notInstRssdId = false;
            $scope.errorMessage = '';

            AdvBranchesService.getBranchSearchData(data)
                .then(function(result) {

                    $scope.instBranchData = result;
                    $scope.totalBranchItems = $scope.instBranchData.length;

                    if (result.length == 0 && data.parentRssdId != null) {
                        $scope.notInstRssdId = true;
                        AdvBranchesService.checkRSSDIDIsTophold(data)
                        .then(function (ret) {
                            if(ret.rSSDId > 0) {
                                $state.go('^.summary.orgs', { rssd: ret.rSSDId });

                                //$scope.errorMessage = 'Parent RSSDID entered is a Tophold. There isn\'t any data to display.';
                            }
                            else
                            {
                                $scope.errorMessage = 'Parent RSSDID entered is not valid.';
                            }
                        });
                    }
                    else if(result.length == 0)
                    {
                        $scope.notInstRssdId = true;
                        $scope.errorMessage = 'There wasn\'t any data found for entered criteria.';
                    }
                    else {
                        var branchCount = 0;
                        var totalDeposits = 0;
                        $scope.totalInstCount = $scope.instBranchData.length;

                        for (var i = 0; i < $scope.instBranchData.length; i++) {
                            branchCount += $scope.instBranchData[i].branches.length;
                            for (var j = 0; j < $scope.instBranchData[i].branches.length; j++) {
                                totalDeposits += $scope.instBranchData[i].branches[j].deposits;
                            }
                        }

                        $scope.branchCount = branchCount;
                        $scope.totalDeposits = totalDeposits;
                    }

                    $scope.searchState = 'loaded';
                });

        };

        $scope.$watch('branchCriteria.marketNumber', function (newValue, oldValue) {

            if (!oldValue)
                $scope.branchCriteria.customMarket = null;

        });

        $scope.$watch('branchCriteria.customMarket', function (newValue, oldValue) {
            if (!oldValue)
                $scope.branchCriteria.marketNumber = null;

        });

        $scope.printView = function () {
            var cityName = '';
            if ($scope.branchCriteria.internationalCity != null) {
                cityName = $scope.branchCriteria.internationalCity.name;
            } else {
                cityName = $scope.branchCriteria.city ? $scope.branchCriteria.city.name : null;
            }
            var data = [
                $scope.branchCriteria.name,
                $scope.branchCriteria.marketNumber,
                $scope.branchCriteria.state ? $scope.branchCriteria.state.fipsId : null,
                $scope.branchCriteria.county ? $scope.branchCriteria.county.countyId : null,
                cityName,
                $scope.branchCriteria.zip,
                $scope.branchCriteria.sdfCode,
                $scope.branchCriteria.customMarket ? $scope.branchCriteria.customMarket.marketId : null,
                $scope.branchCriteria.rssdId,
				$scope.branchCriteria.fdicId,
				$scope.branchCriteria.districtId
            ];
            var reportType = 'branchsearch';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
            $scope.hideReportLoading = true;


            //var data = { type: $scope.type, branches: $scope.selectedBranchRSSDs };// Posting data to php file
            //$http({
            //    method  : 'POST',
            //    url     : '/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData,
            //    data: data, //forms user object
            //    responseType: 'arraybuffer'
            //    //headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
            //}).success(function(response) {
            //         $scope.hideReportLoading = true;
            //        const file = new Blob([response],{ type: 'application/pdf' });

            //        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            //            window.navigator.msSaveOrOpenBlob(file, "BranchSearchResults.pdf");
            //        }
            //        else {
            //            const fileURL = URL.createObjectURL(file);

            //            window.open(fileURL, "_blank");
            //        }                        
            //});
        }


       

    }

})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsBrowseController', AdvInstitutionsBrowseController);

    AdvInstitutionsBrowseController.$inject = ['$scope', '$state', 'StatesService'];

    function AdvInstitutionsBrowseController($scope, $state, StatesService) {

        $scope.hasState = false;
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('advInstitutionsCILoansController', advInstitutionsCILoansController);

    advInstitutionsCILoansController.$inject = ['$scope', '$stateParams', '$timeout', '$templateCache', '$log', 'AdvInstitutionsService', 'toastr'];

    function advInstitutionsCILoansController($scope, $stateParams, $timeout, $templateCache, $log, AdvInstitutionsService, toastr) {
        $scope.cILoansData = [];
        $scope.date = new Date();
        $scope.LoadDdata = false;
        $scope.hhi = "";
        $scope.orgInMarket = "";
        $scope.marketName = "";
        $scope.marketDescr = "";
        $scope.totalMarketCILoans = "";
        $scope.totalmarketShare = "";
        $scope.DataReady = false;

        angular.extend($scope, {
            cILoansData: [],
            HistorybyMarketDataLoaded: false,
            TopHoldClosedDataLoaded: true,
            gatherCILoans: handlegatherCILoans,
        });


        activate();

        function activate() {

        }


        function handlegatherCILoans() {

            $scope.processdata = true;
            AdvInstitutionsService.getHHICILoanAnalysis($scope.criteria.marketNumber).then(function (result) {
                $scope.instLoadData = true;
                //clear out items
                $scope.cILoansData = result.data.resultdata;
                $scope.hhi = result.data.hhi;
                $scope.orgInMarket = result.data.orgInMarket;

                $scope.marketName = result.data.marketName;
                $scope.marketDescr = result.data.marketDescr;
                $scope.totalMarketCILoans = result.data.totalMarketCILoans;
                $scope.totalmarketShare = result.data.totalmarketShare;

                $scope.instDataReady = true;
                $scope.instLoadData = false;
                $scope.processdata = false;


            });

        }

        $scope.showSearchResults = function () {
            console.info('here in the flip');
            $scope.showdetails = true;
            $scope.instDataReady = false;
            $scope.instLoadData = false;
        };




    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsController', AdvInstitutionsController);

    AdvInstitutionsController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log'];

    function AdvInstitutionsController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log) {
        angular.extend($scope, {
            isIndex: isOnIndexPage($state.current),

        });
		
        $scope.searchType = "topholds";
        $scope.criteria = {
            name: null,
            rssd: null,
            fdic: null,
            marketNumber: null,
            international: null,
            state: null,
            county: null,
            city: null,
            zip: null,
            cassidiId: null,
            firmatBranchId: null,
            uninumber: null,
            branchRssd: null,
			sdfCodeId: null,
			searchType: 'tophold'
        };
        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.isIndex = isOnIndexPage(toState);
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

            StatesService.getInternationalCities().then(function (data) {
                $scope.internationalCities = data;
			});

            AdvInstitutionsService.getSDFCodes().then(function (data) {
                $scope.sdfCodes = data;
			});			
			
            AdvInstitutionsService.getCustomMarkets().then(function (data) {
                $scope.customMarkets = data;
            });
        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.institutions";
        }
    }
})();

                

;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsEditBranchController', AdvInstitutionsEditBranchController);

    AdvInstitutionsEditBranchController.$inject = ['$http','$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', '$uibModal', 'toastr', 'uibDateParser', '$timeout', 'AdvBranchesService',  'AdvMarketsService', 'Dialogger','genericService' ];

    function AdvInstitutionsEditBranchController($http, $scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, $uibModal, toastr, uibDateParser, $timeout, AdvBranchesService, AdvMarketsService, Dialogger, genericService) {

        $scope.instData = [];
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
        $scope.dontshowprocessing = true;
		$scope.invalidCityCombination = false;
		$scope.criteria = [];
		$scope.criteria.packetId = null;
		$scope.showFdicUniSearch = false;
		$scope.fdicCandidatesBrs = [];
		$scope.isLoadingUninums = false;

        $scope.saveChanges = function () {
			$scope.dontshowprocessing = false;

            //do the validation no matter which way you are going
            $scope.contProcessing = true;
            $scope.BranchDataReady = false;
            $scope.BranchShowdetails = false;

            var d = new Date();



            if ($scope.invalidCityCombination == true)
            {
                toastr.error("No market found!");
                $scope.contProcessing = false;
			}

			// is firma packet id selected when needed
			if (!$scope.criteria.bypassHistory && $rootScope.FeatureToggles.ChangePacketIntegration && ($scope.criteria.packetId == false || typeof ($scope.criteria.packetId) != 'number') || $scope.criteria.packetId < 0)
			{
				toastr.error("When creating a history, you must select a change packet.");
				$scope.contProcessing = false;
			}

            // check for comma
            if ($scope.criteria.deposits && isNaN($scope.criteria.deposits)) {
                if ($scope.criteria.deposits.indexOf(",") != -1)
                {
                    toastr.error("Deposit value cannot contain a comma!");
                }
                else if ($scope.criteria.deposits.indexOf("$") != -1)
                {
                    toastr.error("Deposit value should not contain the $ symbol!");
                }
                else
                {
                    toastr.error("Deposit value must be numeric!");
                }
                
                $scope.contProcessing = false;
            }

            //verify we have transaction date, name, primary 
            if (!$scope.criteria.parentRssdId) {
                toastr.error("Parent RSSDID is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.parentFDIC) {
                toastr.error("Parent FDIC is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.transactionDateType) {
                toastr.error("Transaction Type must be entered!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.address) {
                toastr.error("Address is required!");
                $scope.contProcessing = false;
            }
            
            //if (!$scope.criteria.docketNumber && $scope.criteria.InstCategoryId == 'T') {
            //    toastr.error("Docket Number is required!");
            //    $scope.contProcessing = false;
            //}

            if (!$scope.criteria.city) {
                toastr.error("City is required!");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.state) {
                toastr.error("State is required!");
                $scope.contProcessing = false;

            }


            if (!$scope.criteria.county) {
                toastr.error("County is required!");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.zip) {
                toastr.error("Zip Code is required!");
                $scope.contProcessing = false;

            }
            else
            {
                if (/^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] *\d[A-Z]\d)$/.test($scope.criteria.zip))
                {
                    
                }
                else
                {
                    toastr.error("Zip Code is invalid!");
                    $scope.contProcessing = false;
                }
            }


            if (!$scope.criteria.district) {
                toastr.error("FRS DISTRICT is required");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.msa) {
                if (!($scope.criteria.msa >= 0)) {
                    toastr.error("MSA is required");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.sodDate) {
                toastr.error("sodDate is required");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.deposits) {
                toastr.error("Branch deposits is required");
                $scope.contProcessing = false;

            }

            //validate the msa and district and the city,state,county combination
            $scope.populateDistrictIDValidateCity();

            if ($scope.invalidCityCombination == true)
            {
                toastr.error('Invalid City/State/County combination!');
                $scope.contProcessing = false;

            }

            if (($scope.criteria.isHeadOffice == false) && ($scope.hasBranches == 0))
            {
                Dialogger.confirm('You do not have any branches created and have not set the is Head office. If you click yes to continue we will default his branch to the Head Office.  Do you want to continue?', null, true).then(function (result) {
                    $scope.contProcessing = result;
                    if ($scope.contProcessing == true) {
                        $scope.criteria.isHeadOffice = true;
                        processchange();
                        
                    }
                    else
                    {
                        $scope.dontshowprocessing = true;
                        $scope.BranchDataReady = true;
                        $scope.BranchShowdetails = true;
                    }
                });
            }
            else
            {
                if ($scope.contProcessing == true) {
                    processchange();
                    
                }
                else {
                    $scope.dontshowprocessing = true;
                    $scope.BranchDataReady = true;
                    $scope.BranchShowdetails = true;
                }
            }
            

           


        };

        $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /^(\d{5}-\d{4}|\d{5})$/;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
                
            }
        };

        function processchange() {
           
                if ($scope.contProcessing == true) {
                    //send the new Tophold to the services later
                    // function postInstitution(id, inst) {
          
                    var BranchUpdateDTO =
                        {
                            id: $scope.criteria.branchId,
                            RSSDId: $scope.criteria.rssdId,
                            BranchRSSD: $scope.criteria.rssdId,
                            TransactionDate: $scope.criteria.transactionDate,
                            ParentRSSD: $scope.criteria.parentRssdId,
                            BranchNum: $scope.criteria.facility,
                            Uninumber: $scope.criteria.uninumber,
                            FirmatId: $scope.criteria.firmatBranchId,
                            isHeadOffice: $scope.criteria.isHeadOffice,
                            Name: $scope.criteria.name,
                            StreetAddress: $scope.criteria.address.toUpperCase(),
                            StateId: $scope.criteria.state.stateId,
                            CountyId: $scope.criteria.county.countyId,
                            CityId: $scope.criteria.cityId,
                            Zipcode: $scope.criteria.zip,
                            DistrictId: $scope.criteria.district,
                            MSA: $scope.criteria.msa,
                            //SODServiceTypeCode: $scope.criteria.fdicServiceTypeCode,
                            Deposits: $scope.criteria.deposits,
                            SODDate: $scope.criteria.sodDate,
                            SpecialtyFlagId: $scope.criteria.specialityFlag.id,
                            MarketId: $scope.criteria.bankingMarketId,
                            CassidiId: $scope.criteria.cassidiId
                        }

                    //if this is a thrift just set the name to the address
                    //if ($scope.criteria.InstCategoryId == 'T')
                    //{
                    //    BranchUpdateDTO.Name = BranchUpdateDTO.StreetAddress;
                    //}

                    var data = {
                        branchRecord: BranchUpdateDTO,
                        latitude: $scope.criteria.latitude,
                        longitude: $scope.criteria.longitude,
                        bypassHistory: $scope.criteria.bypassHistory,
                        transDate: $scope.criteria.historyTransactionDate,
                        transType: $scope.criteria.transactionDateType,
						isFromBankCharter: $scope.isFromBankCharter,
						firmaPacketId: $scope.criteria.packetId
                    }

                    var branchid = $scope.criteria.branchId;

                    processBranch(branchid,data);
                }
        }


        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }


        function processBranch(branchid,data) {




            AdvBranchesService.postBranch(branchid, data).then(function (results) {
                window.scrollTo(0, 0);
                if (results.errorFlag == false) {
                    $scope.InstAdded = true;
                    $scope.THCData = false;
                    if (branchid) {
                        $scope.BranchReportAdded = false;
                        $scope.BranchReportchanged = true;
                        $scope.BranchDataReady = false;
                        $scope.BranchShowdetails = false;
                        $scope.dontshowprocessing = true;
                        AdvBranchesService.getBranchDetail({ branchId: branchid }).then(function (result) {
                            if (result && result != null) {
                                
                                $scope.criteria.facility = result.facility;  //branch num
                                //$scope.criteria.isHeadOffice
                               
                            }
                            else {
                                toastr.success("Branch was updated but we had a reloading issue for the print confirmation screen!");
                            }

                        });


                        toastr.success("Branch was updated");
                        window.scrollTo(0, 0);


                    }
                    else {
                        $scope.BranchReportAdded = true;
                        $scope.BranchReportchanged = false;
                        $scope.BranchDataReady = false;
                        $scope.BranchShowdetails = false;
                        $scope.dontshowprocessing = true;
                        //We created the branch so we need to get the business object generated values
                        //$scope.criteria.branchId = results.branchRecord.branchId;
                        //now get the record back for the results
                        AdvBranchesService.getBranchDetail({ branchId:results.branchRecord.branchId }).then(function (result) 
                        {
                            if (result && result != null) 
                            {
                                $scope.criteria.cassidiId = result.cassidiId;
                                $scope.criteria.firmatBranchId = result.firmatBranchId;
                               // $scope.criteria.bankingMarketId = result.bankingMarketId;
                                $scope.criteria.facility = result.facility;  //branch num
                                //$scope.criteria.isHeadOffice
                                toastr.success("Branch was created");
                                window.scrollTo(0, 0);
                            }
                            else
                            {
                                toastr.success("Branch was created but we had a reloading issue for the print confirmation screen!");
                            }
                           
                        });

                        
                    }

                }
                else {
                    //var errorMessage = [];
                    if (results.messageTextItems.length > 0) {
                        for (var i = 0; i < results.messageTextItems.length; i++) {
                            toastr.error(results.messageTextItems[i]);

                        }
                        $scope.BranchReportAdded = false;
                        $scope.BranchReportchanged = false;
                        $scope.BranchDataReady = true;
                        $scope.BranchShowdetails = true;
                        $scope.dontshowprocessing = true;
                    }

                }


            }, function (err) {
                alert("Sorry. There was an error.");
            });

        }

        $scope.getMSAList = function () {

            var data = {
                districtId: $scope.criteria.district,
                stateId: $scope.criteria.state.stateId,
                countyId: $scope.criteria.county.countyId,
            }

            AdvInstitutionsService.getmsabyDistrictID(data).then(function (results) {
                if (results.msaId != 0)
                    $scope.criteria.msa = results.msaId;

                else
                    $scope.criteria.msa = 0;


            });

        };

        $scope.toggleUninumSearch = function () {
			$scope.showFdicUniSearch = !$scope.showFdicUniSearch;
			if (!$scope.showFdicUniSearch) {
				return;
			}	

			$scope.isLoadingUninums = true;
            AdvInstitutionsService.getFindFdicCandidates($scope.criteria.branchId, $scope.criteria.parentFDIC, $scope.criteria.state.stateId).then(function (data) {
            	$scope.isLoadingUninums = false;
				if (data.length > 0) {
                    $scope.fdicCandidatesBrs = data;
                }
				else {
					//there was an error or no matches were found
					$scope.fdicCandidatesBrs = [];
					toastr.alert("No FDIC branch matches");
				}
			}, function (err) {
				toastr.error('There was an error searching for FDIC branches.');
			});			
		};

		$scope.setAsUninumVal = function (uninumVal, latitude, longitude) {
			$scope.isLoadingUninums = false;
            $scope.criteria.uninumber = uninumVal;
            $scope.criteria.latitude = latitude;
            $scope.criteria.longitude = longitude;
			$scope.toggleUninumSearch();
		}


        $scope.populateDistrictIDValidateCity = function () {

            if ($scope.criteria.state && $scope.criteria.county)
            {
                var data =
				{
					stateFipsId: $scope.criteria.state.stateId,
					countyId: $scope.criteria.county.countyId
				}


                AdvInstitutionsService.getDistrictByLocation(data).then(function (data) {
                    if (data.errorFlag == false) {
                        //now update the  instUpdDTO object
                        $scope.criteria.district = data.districtId;
                        $scope.getMSAList();
                    }
                    else {
                        //there was an error toast and exit
                        $scope.criteria.district = 0;
                    }
                }, function (err) {
                    toastr.error('There was an error finding the District and MSA information!');
                });


                if ($scope.criteria.city)
                {
                    var data =
                    {
                        stateId: $scope.criteria.state.stateId,
                        countyId: $scope.criteria.county.countyId
                    }

                    //populate the city from the county and state dropdown
                    genericService.getCities(data).then(function (result) {
                        $scope.criteria.county.city = result;

                        var foundCity = _.find($scope.criteria.county.city, { city: $scope.criteria.city.toUpperCase() });

                        if (foundCity) {
                            $scope.criteria.cityId = foundCity.cityId;
                            $scope.criteria.city = foundCity.city;
                            // toastr.info('Valid City / State / County combination!');
                            $scope.invalidCityCombination = false;
                            //since we have a valid city /State / Count combination get the market
                            AdvMarketsService.getMarketNumber($scope.criteria.cityId).then(function (data) {
                                $scope.criteria.bankingMarketId = data;
                            });
                        }
                        else {
                            //need to ask if we need to goto the add city screen
                            //AdvMarketsService.openAddCityToMarket($scope.criteria.state.stateId,
                            //    $scope.criteria.county.countyId,
                            //    $scope.criteria.city);
                            //toastr.info('Invalid City/State/County combination!');
                            $scope.criteria.bankingMarketId = '';
                            $scope.invalidCityCombination = true;



                        }

                    });

                   
                }
                else
                {
                    //toastr.info('State/County/City information was not provided.');
                    $scope.criteria.bankingMarketId = '';
                    $scope.invalidCityCombination = true;
                }
                //now go validate the city
                
            }
            else
            {
                //toastr.info('State/County/City information was not provided.');
                $scope.criteria.bankingMarketId = '';
                $scope.invalidCityCombination = true;
            }
            


        };

        $scope.UpdateCounties = function () {
            //$scope.criteria.city = null;
            $scope.criteria.county = null;

            genericService.getCounties($scope.criteria.state.stateId).then(function (result) {
                $scope.criteria.state.counties = result;
            });




        }

        $scope.$on('new-city-added', function (event, args) {
            $scope.criteria.bankingMarketId = '';
            //we just added a new city we need to refresh the state info
            StatesService.statesPromise.then(function (result) {

                var foundCity = _.find($scope.criteria.county.city, { city: $scope.criteria.city.toUpperCase() });

                if (foundCity) {
                    $scope.criteria.cityId = foundCity.cityId;
                    $scope.criteria.city = foundCity.city;
                    toastr.info('Valid City / State / County combination!');

                    //since we have a valid city /State / Count combination get the market
                    AdvMarketsService.getMarketNumber($scope.criteria.cityId).then(function (data) {
                        $scope.criteria.bankingMarketId = data;
                    });
                }

                toastr.error('Created the New City and Associated it to the Market ' + $scope.criteria.bankingMarketId);
            });


        });

        $scope.cancel = function () {
            $scope.$dismiss();
			$state.reload();
        };
        
        $scope.populateServiceType = function () {
            //if ($scope.criteria.specialityFlag.name == 'NONE')
            //{
            //    $scope.criteria.fdicServiceTypeCode = '11';
            //}
            //else
            //{
            //    $scope.criteria.fdicServiceTypeCode = $scope.criteria.specialityFlag.id;
            //}           
        };

 
        activate();

        function activate() {
            //move to the top of the screen and set focus on the RSSDID
             // CRG - 04/21/2019 - This raises an error and I see no reason to have this call
            //$timeout(function () {
            //    $('[id="historyTransactionDate _input"]')[0].focus();

            //}, 750);

			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}

            window.scrollTo(0, 0);

            $scope.dontshowprocessing = false

            genericService.getStates().then(function (result) {
                var criteria = [];
                $scope.criteria = [];
                $scope.states = result;
                $scope.statesLoaded = true;
                $scope.instDataReady = true;
                $scope.showHistoryOption = true;

                if ($state.params.mode == 'BranchOpening') {
                    //need to move this to a method so we can call this later
					AdvBranchesService.getSpecialityFlags(false)
						.then(function (data) { // NOTE: pass in false to getSpecialityFlags to prevent the legacy -1, NONE value from being included
                        $scope.specialityFlag = data;
                        $scope.criteria.specialityFlag = data;
                        $scope.recMode = "Add";
                        $scope.BranchAdded = false;
                        $scope.Branchchanged = false;
                        $scope.BranchDataReady = true;
                        $scope.criteria.transactionDateType = 2;
                        $scope.criteria.bypassHistory = false;
                        $scope.showHistoryOption = false;
                        $scope.BranchShowdetails = true;
                        $scope.BranchDataReady = true;
                        $scope.isFromBankCharter = true;
                        if ($state.params.Bankcriteria)
                        {
                        
                            if ($state.params.Bankcriteria.InstCategoryId == 'B' || $state.params.Bankcriteria.class == 'BANK')
                            {
                                $scope.pageTitle = "Bank Head Office";

                                
                                $scope.criteria.InstCategoryId = 'B';
                            }
                            else
                            {
                                $scope.pageTitle = "Thrift Head Office";
                            
                                $scope.criteria.InstCategoryId = 'T';
                            }
                        
                            //so we need to know if the parent org has branchs or this is the first one
                            $scope.criteria.parentRssdId = $state.params.BankRSSDID
                            AdvInstitutionsService.getInstitutionData({ rssdId: $scope.criteria.parentRssdId, getDetail: true, getBranches: true, getOperatingMarkets: false, getHistory: false }).then(function (result) {

                                $scope.dontshowprocessing = true;

                                if (result && result != null) {
                                    //result.data.instData
                                    $scope.hasBranches = result.branches.length;
                                    $scope.criteria.parentName = result.definition.name;
                                    $scope.criteria.parentFDIC = result.definition.fdicCert;
                                }
                            });

                            $scope.criteria.bypassHistory = $state.params.Bankcriteria.bypassHistory;
                            $scope.criteria.historyTransactionDate = $state.params.Bankcriteria.historyTransactionDate;
                            $scope.criteria.historyTransactionDate = $state.params.Bankcriteria.historyTransactionDate;

                            $scope.criteria.transactionDateType = $state.params.Bankcriteria.transactionDateType
                            $scope.criteria.uninumber = 0;

                            $scope.criteria.specialityFlag = _.find($scope.specialityFlag, { id: 11 });
                            //$scope.criteria.fdicServiceTypeCode = 11;
                            $scope.criteria.isHeadOffice = true;
                            //we need to get this number how?
                            $scope.criteria.firmatId = $state.params.Bankcriteria.firmatId;
                            $scope.criteria.branchRSSD = $state.params.Bankcriteria.branchRSSD;
                            $scope.criteria.branchNum = $state.params.Bankcriteria.branchNum;
                            $scope.criteria.facility = $state.params.Bankcriteria.facility;
                            $scope.criteria.parentFDIC = $state.params.Bankcriteria.fdicCert;
                            $scope.criteria.docketNumber = $state.params.Bankcriteria.docketNumber;
                            $scope.criteria.name = $state.params.Bankcriteria.name;
                            $scope.criteria.state = $state.params.Bankcriteria.state;
                            //now get the county dropdown list

                            $scope.criteria.county = $state.params.Bankcriteria.county ;
                            //$scope.criteria.city = $state.params.Bankcriteria.city;
                            $scope.criteria.cityId = $state.params.Bankcriteria.city.cityid;
                            $scope.criteria.city = $state.params.Bankcriteria.city.city;
                            $scope.criteria.district = $state.params.Bankcriteria.district;
                            $scope.criteria.msa = $state.params.Bankcriteria.msa;
                            $scope.criteria.deposits = '0.000';
                            $scope.criteria.sodDate = $state.params.Bankcriteria.sodDate;
                            $scope.criteria.branchId = null;
                            //now populate the market number
                            $scope.populateDistrictIDValidateCity();

                        }
                    });
                
                }
                else if( $state.params.mode== 'BranchOpeningNonHead')   
                {
                    AdvBranchesService.getSpecialityFlags(false).then(function (data) {  // NOTE: pass in false to getSpecialityFlags to prevent the legacy -1, NONE value from being included
                        $scope.specialityFlag = data;
                        $scope.criteria.specialityFlag = data;
                        $scope.recMode = "Add";
                        $scope.BranchAdded = false;
                        $scope.Branchchanged = false;
                        $scope.BranchDataReady = true;
                        $scope.criteria.transactionDateType = 2;
                        $scope.criteria.bypassHistory = false;
                        $scope.showHistoryOption = false;
                        $scope.BranchShowdetails = true;
                        $scope.BranchDataReady = true;
                        $scope.isFromBankCharter = false;
                        
                        if ($state.params.Bankcriteria) {
                            $scope.criteria.parentRssdId = $state.params.BankRSSDID;
                            if ($state.params.Bankcriteria.InstCategoryId == 'B' || $state.params.Bankcriteria.class == 'BANK') {
                                $scope.pageTitle = "Bank Branch Opening";
                                $scope.criteria.InstCategoryId = 'B';
                            }
                            else {
                                $scope.pageTitle = "Thrift Branch Opening";
                                $scope.criteria.InstCategoryId = 'T';
                            }
                            
                            $scope.criteria.parentFDIC = $state.params.Bankcriteria.fdicCert;
                            $scope.criteria.docketNumber = $state.params.Bankcriteria.docketNumber;
                            $scope.criteria.bypassHistory = $state.params.Bankcriteria.bypassHistory;
                            $scope.criteria.transactionDateType = $state.params.Bankcriteria.transactionDateType
                            $scope.criteria.uninumber = 0;
                            //getting tophold information
                            AdvInstitutionsService.getInstitutionData({ rssdId: $scope.criteria.parentRssdId, getDetail: true,  getBranches: true, getOperatingMarkets: false, getHistory: false }).then(function (result){

                                $scope.dontshowprocessing = true;

                                if (result && result != null) {
                                    //result.data.instData
                                    $scope.hasBranches = result.branches.length;
                                    //something happen with the data that was passed in so use the look up information
                                    if ($scope.criteria.parentFDIC == null)
                                    {
                                        $scope.criteria.parentFDIC = result.definition.fdicCert;
                                        $scope.criteria.docketNumber = result.definition.docketNumber;
                                    }
                                }
                            });

                            //we need to get this number how?
                            $scope.criteria.deposits = '0.000';
                            $scope.criteria.uninumber = 0;
                            $scope.criteria.sodDate = "06/30/2023";
                            $scope.criteria.branchId = null;
                            $scope.criteria.transactionDateType = 2;
                            $scope.criteria.isHeadOffice = false;
                            $scope.criteria.facility = null;
                            $scope.criteria.specialityFlag = _.find($scope.specialityFlag, { id: 11 });
                            //$scope.criteria.fdicServiceTypeCode = 11;
                            $scope.criteria.parentName = $state.params.Bankcriteria.name;
                        }
                        else
                        {
                            $scope.criteria.parentRssdId = $state.params.rssd;
                            //look up the inst info
                            AdvInstitutionsService.getEditInstitutionData({ rssdId: $state.params.rssd }).then(function (result) {
                        if (result && result != null) {

                                    if (result.entityTypeCode == 'BANK') {
                                        $scope.pageTitle = "Bank Branch Opening";
                                        $scope.criteria.InstCategoryId = 'B';
                                    }
                                    else {
                                        $scope.pageTitle = "Thrift Branch Opening";
                                        $scope.criteria.InstCategoryId = 'T';
                                    }
                                    $scope.criteria.parentFDIC = result.fdicCert;
                                    $scope.criteria.docketNumber = result.docketNumber;
                                    $scope.criteria.uninumber = 0;
                                    $scope.isFromBankCharter = false;
                                    $scope.criteria.parentName = result.name;
                                    $scope.criteria.deposits = '0.000';
                                    $scope.criteria.sodDate = "06/30/2023";
                                    $scope.criteria.branchId = null;
                                    $scope.criteria.transactionDateType = 2;
                                    $scope.criteria.isHeadOffice = false;
                                    $scope.criteria.facility = null;
                                    $scope.criteria.specialityFlag = _.find($scope.specialityFlag, { id: 11 });
                                    //$scope.criteria.fdicServiceTypeCode = 11;
                                }
                            });
                            
						}
						$scope.dontshowprocessing = true;
                    });
                }
                else {
                    AdvBranchesService.getBranchDetail({ branchId: $state.params.branchId }).then(function (result) {

                        $scope.dontshowprocessing = true;

                        if (result && result != null) {
                            //countyFIPSNum
                            
                            var criteria = result;
                            var preCriteria = result;
                            criteria.type = result.type;
                            criteria.BranchType = result.class == "BANK" ? "Bank" : "Thrift";
                            criteria.InstCategoryId = result.class == "BANK" ? "B" : "T";
                            $scope.pageTitle = criteria.BranchType + " Branch Attribute Update";
                            criteria.state = _.find($scope.states, { stateId: result.stateId });
                            genericService.getCounties(result.stateId).then(function (resultCounty) {
                                criteria.state.counties = resultCounty;
                                criteria.county = _.find(criteria.state.counties, { countyId: result.countyId });
                            });
                            
                            criteria.city = result.city;
                            criteria.cityId = result.cityId;

                            //need to move this to a method so we can call this later
                            AdvBranchesService.getSpecialityFlags(false).then(function (data) { // NOTE: pass in false to getSpecialityFlags to prevent the legacy -1, NONE value from being included
                                $scope.sdfCodes = data;
                                $scope.specialityFlag = $scope.sdfCodes;
                                criteria.specialityFlag = _.find($scope.specialityFlag, { id: result.specialityFlagId });
                                //if (!criteria.fdicServiceTypeCode)
                                //{
                                //    criteria.fdicServiceTypeCode = 11;
                                //}
                                criteria.bypassHistory = false;
                                $scope.BranchShowdetails = true;
                                $scope.criteria = criteria;
                                preCriteria = angular.copy(criteria);
                                $scope.pretophold = preCriteria;
                                $scope.recMode = "Edit";
                                $scope.BranchAdded = false;
                                $scope.Branchchanged = false;
                                $scope.criteria.transactionDateType = 2;
                                $scope.BranchDataReady = true;
                                if ($scope.criteria.deposits == 0)
                                {
                                    $scope.criteria.deposits = '0.00';
                                }
                            });
                        }
                        $scope.institutionLoaded = true;
                    });
                }




            });







        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.institutions";
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsEditBranchGeocodeController', AdvInstitutionsEditBranchGeocodeController);

    AdvInstitutionsEditBranchGeocodeController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', 'AdvBranchesService', '$log', '$uibModal', 'toastr', '$uibModalInstance', 'uibDateParser'];

    function AdvInstitutionsEditBranchGeocodeController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, AdvBranchesService, $log, $uibModal, toastr, $uibModalInstance, uibDateParser) {

        $scope.instData = [];
        $scope.processing = false;
        //if (!$scope.criteria) { $scope.criteria = [];}
		//$scope.criteria.transactionDateType = 2; 
        var preCriteria;

        $scope.institutionLoaded = false;
        $scope.saveChanges = function () {
        $scope.entrydate = new Date();


            var geoData = {
                CountyDivGeoId: $scope.criteria.countyDivGeoId,
                GeocodeAddress: $scope.criteria.geocodeAddress ,
                GeocodeStatus: $scope.criteria.locatorStatus.id,
                Latitude: $scope.criteria.latitude,
                Longitude: $scope.criteria.longitude
            };


            var updateDate = {
                branchId: $state.params.branchId,
                geocode: geoData
            }

            $scope.processing = true;

            AdvBranchesService.postupdateGeocode(updateDate).then(function (results) {

                $scope.processing = false;

                if (results.errorFlag == false) {
                    toastr.success('Successfully Updated Bank Branch Geocode!');
                    $scope.displayConfirmation = true;

                }
                else {
                    //var errorMessage = [];
                    if (results.messageTextItems.length > 0) {
                        for (var i = 0; i < results.messageTextItems.length; i++) {
                            toastr.error(results.messageTextItems[i]);
                        }
                    }
                }
            }, function (err) {
                alert("Sorry. There was an error.");
            });
            
        };

        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        $scope.cancel = function () {

            $scope.$dismiss();
            //$state.('root.adv.institutions.summary', { rssd: $scope.criteria.rssdId, isTophold: true });
            $state.reload();
        };


        activate();

        function activate() {
            //load the branch details
            StatesService.statesPromise.then(function (result) {
                var criteria = [];
                $scope.states = result;
                $scope.processing = true;

                AdvBranchesService.getBranchDetail({ branchId: $state.params.branchId }).then(function (result) {

                    $scope.processing = false;

                    if (result && result != null) {
                        var criteria = result;
                        var preCriteria = result;
                        criteria.type = result.type;
                        criteria.BranchType = result.class == "BANK" ? "Bank" : "Thrift";
                        criteria.InstCategoryId = result.class == "BANK" ? "B" : "T";
                        $scope.pageTitle = criteria.BranchType + " Branch Attribute Update";
                        criteria.state = _.find($scope.states, { stateId: result.stateId });
                        criteria.county = _.find(criteria.state.counties, { countyId: result.countyId });
                        criteria.city = _.find(criteria.state.cities, { cityId: result.cityId }).city;
                        criteria.cityid = _.find(criteria.state.cities, { cityId: result.cityId }).cityid;

                        AdvBranchesService.getSpecialityFlags(false).then(function (data) { // NOTE: pass in false to getSpecialityFlags to prevent the legacy -1, NONE value from being included
                            $scope.sdfCodes = data;
                            $scope.specialityFlag = $scope.sdfCodes;
                            criteria.specialityFlag = _.find($scope.specialityFlag, { id: result.specialityFlagId });
                            $scope.branchcriteria = criteria;

                            AdvBranchesService.getInstitutionName($scope.branchcriteria.parentRssdId).then(function (data) {
                                $scope.branchcriteria.parentName = data;
                            });
                        });
                    }
                    else {
                        toastr.error('Unable to load the Branch details!');
                    }
                });

            });           
           

            AdvBranchesService.getLocatorStatuses().then(function (data) {
                $scope.locatorStatuses = data;
                AdvBranchesService.getBranchGeoCode({ branchId: $state.params.branchId }).then(function (result) {
                    if (result && result != null) {

                        var criteria = result;
                        criteria.locatorStatus = _.find($scope.locatorStatuses, { id: result.geocodeStatus });

                        $scope.transactionDateType = 2;
                        $scope.bypassHistory = false;
                        $scope.displayConfirmation = false;


                        $scope.criteria = criteria;

                        //populate the precriteria
                        preCriteria = angular.copy(criteria);
                        $scope.pregeocode = preCriteria;

                        
                        

                    }

                });
            });

        }


    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsEditController', AdvInstitutionsEditController);

    AdvInstitutionsEditController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', '$uibModal', 'toastr', '$uibModalInstance', 'uibDateParser', 'rssdId'];

    function AdvInstitutionsEditController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, $uibModal, toastr, $uibModalInstance, uibDateParse, rssdId) {
        $scope.txnIds = [];
        $scope.tophold = [];

        $scope.instData = [];
		$scope.selectRecord = false;
		$scope.criteria.transactionDateType = 2;

        $scope.institutionLoaded = false;
        $scope.saveChanges = function () {
            $uibModalInstance.close({ institution: $scope.criteria }); //, feedbackType: $scope.feedbackType });
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.saveChanges = function () {
            if ($scope.recMode == "Add Tophold ") {
                if ($scope.txnIds.length == 0)
                { Dialogger.alert("No Pending Transactions have been selected!"); }
                else {
                    $uibModalInstance.close({ institution: $scope.criteria, transactionId: $scope.txnIds[0] });
                }
            }
            else {
                $uibModalInstance.close({ institution: $scope.criteria, transactionId: -1 });
            }
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.toggle = function (id) {
            $scope.txnIds = []
            $scope.txnIds.push(id);
        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };

        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = []
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

        $scope.maxLengthCheck = function (object) {
            if (object.value.length > object.maxLength)
                object.value = object.value.slice(0, object.maxLength)
        };

        $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /[0-9]|\./;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();

            }
        };
        

        activate();

        function activate() {

            $timeout(function () {
                $('[id="historyTransactionDate _input"]')[0].focus();

            }, 750);

            window.scrollTo(0, 0);

            AdvInstitutionsService.getSDFCodes().then(function (data) {
                $scope.sdfCodes = data;
            });
            StatesService.statesPromise.then(function (result) {
                var criteria = [];
                $scope.states = result;
                $scope.statesLoaded = true;
                $scope.instDataReady = true;
                if (rssd == null || rssd == '') {
                    $scope.recMode = "Charter";
                    $scope.runDate = new Date();
                    
                    $scope.criteria.InstCategoryId = '';
                    //if bank - weight - 1 charter - 200
                    if (criteria.InstCategoryId == 'B')
                    {
                        $scope.criteria.hhiWeight = '1';
                        $scope.criteria.charterTypeCode = '200';
                    }
                    else
                    {
                        //else thrift weight .5  charter - 300
                        $scope.criteria.hhiWeight = '.5';
                        $scope.criteria.charterTypeCode = '300';
                    }

                    


                    $scope.runDate = new Date();
                    $scope.showPendingTransactions = true;
                }
                else {

                    AdvInstitutionsService.getEditInstitutionData({ rssdId: rssdId.rssd }).then(function (result) {
                        if (result && result != null) {

                            var criteria = result;
                            criteria.type = result.type;
                            criteria.state = _.find($scope.states, { stateId: result.stateId });
                            criteria.county = _.find(criteria.state.counties, { countyId: result.countyId });
                            criteria.city = _.find(criteria.state.cities, { cityId: result.cityId });
                            criteria.sdfCode = _.find($scope.sdfCodes, { name: result.sdf });
                            //criteria.transactionDateType = 1;
							criteria.transactionDateType = 2;
                            criteria.bypassHistory = false
                            $scope.instDataReady = true;
                            $scope.criteria = criteria;
                            $scope.recMode = "Edit ";
                           
                        }
                        $scope.institutionLoaded = true;
                    });
                }

            });

           
          

        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.institutions";
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsFHCListController', AdvInstitutionsFHCListController);

    AdvInstitutionsFHCListController.$inject = ['$scope', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', '$window'];

    function AdvInstitutionsFHCListController($scope, $stateParams, $timeout, $templateCache, AdvInstitutionsService, $window) {
        $scope.instFHCData = [];
        $scope.instFHCDataReady = false;
        $scope.date = new Date();

        $scope.sortType = 'topholdName';
        $scope.sortReverse = false;
        $scope.searchInst = '';

        // Need to get user friendly names from Ids

        $scope.customMarket = $stateParams.customMarket;


        activate();

        function activate() {

            AdvInstitutionsService.getFHCorg().then(function (result) {
                $scope.instFHCData = result;
                $scope.instFHCDataReady = true;

            });
        }

        $scope.printView = function () {
            var data = [
                $scope.searchInst,
                $scope.sortType,
                !$scope.sortReverse
            ];
            var reportType = 'holdingcompanies';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

        }

    }

    angular
      .module('app')
        .filter('filterByProperties', function () {
        /* array is first argument, each addiitonal argument is prefixed by a ":" in filter markup*/
        return function (dataArray, searchTerm, propertyName) {
            if (!dataArray) return;            
            if (!searchTerm) {
                return dataArray
            } else {                
                var term = searchTerm.toLowerCase();
                return dataArray.filter(function (item) {
                    return item[propertyName[0]].toLowerCase().indexOf(term) > -1 || item[propertyName[1]].toLowerCase().indexOf(term) > -1 || item[propertyName[2]].toString().indexOf(term) > -1;
                });
            }
        }
    });



})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsFinderController', AdvInstitutionsFinderController);

    AdvInstitutionsFinderController.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'AdvInstitutionsService', 'StatesService', '$timeout', 'AdvBranchesService', '$sce', '$window', 'toastr'];

    function AdvInstitutionsFinderController($rootScope, $scope, $state, $stateParams, AdvInstitutionsService, StatesService, $timeout, AdvBranchesService, $sce, $window, toastr) {

        window.document.getElementById("searchName").focus();
        $scope.criteriaValue = [];
        $scope.searchType = 'Institutions';
        $scope.inputChangedPromise = null;
        $scope.instData = [];
        $scope.searchState = 'initial';
        $scope.totalInstItems = 0;
        $scope.instItemsPerPage = 50;
        $scope.currentInstPage = 1;
        $scope.instPageSize = 30;
        $scope.hiddeCriteria = false;
        $scope.instBranchData = [];
        $scope.totalBranchItems = 0;
        $scope.branchItemsPerPage = 50;
        $scope.currentBranchPage = 1;

        $scope.scrollLoadDefaultCount = 10;
        $scope.scrollLoadBatchSize = 5;
        $scope.scrollLoadCount = $scope.scrollLoadDefaultCount;
        $scope.totalInstCount = 0;
		$scope.showMoreLinkVisible = false;
		$scope.newSearchStarted = false;
		$scope.getData = getData;


        $scope.criteriaEntered = function() {
            return $scope.criteria.name != null ||
                $scope.criteria.rssd != null ||
                $scope.criteria.fdic != null ||
                $scope.criteria.marketNumber != null ||
                $scope.criteria.state != null ||
                $scope.criteria.county != null ||
                $scope.criteria.zip != null ||
                $scope.criteria.sdfCode != null ||
                $scope.criteria.internationalCity != null ||
                $scope.criteria.regulator != null ||
                $scope.criteria.districtId;
        };

        $scope.displayCriteria = function (value) {
            $scope.hiddeCriteria = !value;

        };
        $scope.clearCriteria = function () {
            $scope.criteria.name = null;
            $scope.criteria.rssd = null;
            $scope.criteria.fdic = null;
            $scope.criteria.marketNumber = null;
            $scope.criteria.state = null;
            $scope.criteria.county = null;
            $scope.criteria.zip = null;
            $scope.criteria.sdfCode = null;
            $scope.criteria.internationalCity = null;
			$scope.searchState = 'initial';
            $scope.criteria.districtId = null;
            $scope.criteria.regulator = null;
        };

        $scope.internationalClear = function () {
            $scope.criteria.county = null;
            $scope.criteria.state = null;
            $scope.criteria.city = null;
        }

        $scope.updatePagination = function()
        {
            updatePaginationData();
        }

        $scope.UpdateCountysAndCitys = function ()
        {
            $scope.criteria.city = null;
            $scope.criteria.county = null;

            var data = {
                stateFIPSId: $scope.criteria.state.fipsId
            };
            StatesService.getCityNames(data).then(function (result) {
                $scope.criteria.state.cities = result;
            });
            StatesService.getCountySummaries(data).then(function (result) {
                $scope.criteria.state.counties = result;
            });

        }


        $scope.instPageCount = function () {
            return Math.ceil($scope.instData.length / $scope.instItemsPerPage);
		};

		$scope.getOrgNameFromPartial = function (partialName) {
			return AdvInstitutionsService.getOrgNameFromPartial(partialName, 10);
		}


        $scope.resetLoadMoreCounter = function () { $scope.scrollLoadCount = $scope.scrollLoadDefaultCount; };

        $scope.loadMoreOnWindowScroll = function (ignoreWindowPosition) {
            $scope.$apply(function () {
                if (($scope.scrollLoadCount < $scope.totalInstCount) && ($(window).scrollTop() > $(document).height() - $(window).height() - 325)) {
                    $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                    $scope.searchState = 'scrollLoading'; 
                }
            });
        }

        $scope.loadMoreOnLinkClick = function () {
            if ($scope.scrollLoadCount < $scope.totalInstCount) {
                $scope.scrollLoadCount = $scope.scrollLoadCount + $scope.scrollLoadBatchSize;
                $scope.searchState = 'scrollLoading';
            }
        }

        $scope.onLoadMoreComplete = function () {
            $scope.clearLoadingMoreMsg();
        }

        $scope.clearLoadingMoreMsg = function () {
            $timeout(function () { $scope.searchState = 'loaded'; }, 3000);
        }

        activate();

        function activate() { 

            AdvInstitutionsService.getRegulators().then(function (result) {
                $scope.regulators = result;
            });

            var data = {
                includeDC: true,
                includeTerritories: true
            };
            StatesService.getStateSummaries(data).then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

             getData();

             
            $scope.SearchOrgSubmit = function () {		
				$scope.newSearchStarted = true; // flag this as a new report so that we clear search field
				$scope.instData = [];
				$scope.scrollLoadCount = $scope.scrollLoadDefaultCount;
				$('#quickSearch').val(''); // clear the form field and trigger events
				$scope.getData(); 				
            };

            $scope.SearchHistoricOrgs = function () {
                historicInstSearch();
            }
            

            angular.element($window).on('scroll', $scope.loadMoreOnWindowScroll);
            $scope.$on('$destroy', function () {
                angular.element($window).off('scroll', $scope.loadMoreOnWindowScroll);
            });

		}		

        function getParams() {
                var params = {
                    name: $scope.criteria.name,
                    rssd: $scope.criteria.rssd,
                    fdic: $scope.criteria.fdic,
                    marketNumber: $scope.criteria.marketNumber,
                    stateId: $scope.criteria.internationalCity != null ? 0 : ($scope.criteria.state ? $scope.criteria.state.fipsId : null),
                    countyId: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                    cityName: $scope.criteria.internationalCity != null
                                ? $scope.criteria.internationalCity.name
                                : ($scope.criteria.city != null
                                ? $scope.criteria.city.name : null),
                    zip: $scope.criteria.zip,
					sdfCodeId: $scope.criteria.sdfCode,
                    districtId: $scope.criteria.districtId,
                    regulatorId: $scope.criteria.regulator != null ? $scope.criteria.regulator.regulatorId: -1
            };

            return params;
        }
        function getData() {
            $scope.test = $scope.criteria.regulator;
            var params = getParams();
            $scope.lastSearchParams = params;
            $scope.contProcessing = true;
            $scope.historySearchEnabled = false;

            if ($scope.criteria.marketNumber != null) {
                if (($scope.criteria.marketNumber.toString().indexOf(',') > -1)) {
                    toastr.error("You cannot enter multiple Market Numbers!");
                    $scope.contProcessing = false;
                }
            }

            if ($scope.contProcessing == true) {               
                if (params.name != null ||
                    params.rssd != null ||
                    params.fdic != null ||
                    params.marketNumber != null ||
                    params.stateId != null ||
                    params.countyId != null ||
                    params.cityName != null ||
                    params.zip != null ||
					params.sdfCodeId != null ||
                    params.districtId != null ||
                    params.regulatorId != -1) {
                    $scope.searchState = 'loading';

                    if (params.rssd == null &&
                        params.fdic == null &&
                        params.marketNumber == null &&
                        params.zip == null &&
                        params.sdfCodeId == null) {
                            $scope.historySearchEnabled = true
                    } 

                    AdvInstitutionsService.getNonHHIInstitutionsSearchData(params)
                    .then(function (result) {

                        $scope.instData = result;
                        $scope.totalInstItems = $scope.instData.length;
                        $scope.instDataPages = _.chunk($scope.instData, $scope.instItemsPerPage);
                        $scope.searchState = 'loaded';
                        $scope.totalInstCount = $scope.instData.length;
                        buildCreteriaValue(params);
                    });

                } else {
                    $scope.instData = [];
                    $scope.instDataReady = false;
                    $scope.totalInstItems = 0;
                    $scope.instItemsPerPage = 50;
                    $scope.currentInstPage = 1;
                    $scope.instDataPages = [];
                }
            }

            

        }
        function buildCreteriaValue(data) {
            var code = _.find($scope.sdfCodes, { id: data.sdfCodeId });

            $scope.criteriaValue = {
                name: data.name,
                marketNumber: data.marketNumber,
                state: data.stateId ? $scope.criteria.state.name : null,
                county: data.countyId ? $scope.criteria.county.countyName : null,
                city: $scope.criteria.city != null ? $scope.criteria.city.name : null,
                zip: data.zip,
                internationalCity:  $scope.criteria.internationalCity != null
                            ? $scope.criteria.internationalCity.name : null,
				sdfCode: (code != null ? code.name + "-" + code.description : null),
                districtId: $scope.criteria.districtId,
                regulatorId: $scope.criteria.regulator != null ? $scope.criteria.regulator.name : null
            }
        }

        function historicInstSearch()
        {
            var searchCriteria = $scope.criteria;
            $state.go('root.adv.history.institutions', { transferCriteria: searchCriteria });
        }

        $scope.$watch('criteria.customMarket', function (newValue, oldValue) {
            if (!oldValue)
                $scope.criteria.marketNumber = null;

        });

        // This is for the Sentinal directive to capture sort column
        $scope.applyChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.sortBy = sortBy.sort.predicate;
                $scope.asc = !sortBy.sort.reverse;
            } else {
                $scope.sortBy = 'name';
                $scope.asc = true;
			}
			$scope.newSearchStarted = false;
        }

        $scope.printView = function () {

            var qs = document.getElementById('quickSearch');

            var data = [
                $scope.criteria.name,
                $scope.criteria.rssd,
                $scope.criteria.fdic,
                $scope.criteria.marketNumber,
                $scope.criteria.state ? $scope.criteria.state.fipsId : null,
                $scope.criteria.county ? $scope.criteria.county.countyId : null,
                $scope.criteria.internationalCity != null
                            ? $scope.criteria.internationalCity.name
                            : ($scope.criteria.city != null
                            ? $scope.criteria.city.name : null),
                $scope.criteria.internationalCity != null ? true : false,
                $scope.criteria.zip,
                $scope.criteria.sdfCode,
                qs.value,
                $scope.sortBy,
				$scope.asc,
                $scope.criteria.districtId,
                $scope.criteria.regulator != null ? $scope.criteria.regulator.regulatorId : null
            ];
            var reportType = 'institutionsearch';
            
            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

        }
    }

    angular
        .module('app')
            .directive('stSentinel', function () {
            return{
                require:'^stTable',
                scope:{
                    onChange:'&stSentinel'
                },
                link:function(scope, element, attr, stTable){
					scope.$watchGroup(
						[
							function () { return stTable.tableState(); },
							function () { return scope.$parent.newSearchStarted }
						]
						, function (newVals, oldVals, scope) {
							if (newVals[1] == true && newVals[1] != oldVals[1]) { // new search started
								var tableState;
								tableState = stTable.tableState();
								tableState.search.predicateObject = {};
								tableState.pagination.start = 0;						
							}
                            scope.onChange({sortBy: newVals[0]});
                        }
                        , true)
                }
            }
        });

    angular
      .module('app')
        .filter('instFilter', function () {
            return function (dataArray, searchTerm) {
                if (!dataArray) return;
                if (searchTerm.$ == undefined) {
                    return dataArray
                } else {
                    var term = searchTerm.$.toLowerCase();
                    return dataArray.filter(function (item) {
                        return checkVal(item.name, term)
                            || checkVal(item.county, term)
                            || checkVal(item.city, term)
                            || checkVal(item.rssdId.toString(), term)
                            || _.find(item.orgs, function (org) {
                                return checkVal(org.name, term)
                                || checkVal(org.county, term)
                                || checkVal(org.city, term)
                                || checkVal(org.rssdId.toString(), term)
                                });
                    });
                }
            }

            function checkVal(val, term)
            {
                if (val == null || val == undefined)
                    return false;

                return val.toLowerCase().indexOf(term) > -1;
            }
		});

	/////////////////////
	//angular
	//	.module('smart-table')
	//	.directive('stBoundSearch', ['stConfig', '$timeout', '$parse', function (stConfig, $timeout, $parse) {
	//		return {
	//			require: ['^stTable', 'ngModel'],
	//			link: function (scope, element, attr, supportCtrls) {
	//				var ctrl = supportCtrls[0];
	//				var fldModel = supportCtrls[1];
	//				var tableCtrl = ctrl;
	//				var promise = null;
	//				var throttle = attr.stDelay || stConfig.search.delay;
	//				var event = attr.stInputEvent || stConfig.search.inputEvent;

	//				attr.$observe('stBoundSearch', function (newValue, oldValue) {
	//					var input = element[0].value;
	//					if (newValue !== oldValue && input) {
	//						ctrl.tableState().search = {};
	//						tableCtrl.search(input, newValue);
	//					}
	//				});

	//				//table state -> view
	//				scope.$watch(function () {
	//					return ctrl.tableState().search;
	//				}, function (newValue, oldValue) {
	//					var predicateExpression = attr.stBoundSearch || '$';
	//					if (newValue.predicateObject && $parse(predicateExpression)(newValue.predicateObject) !== element[0].value) {
	//						element[0].value = $parse(predicateExpression)(newValue.predicateObject) || '';
	//					}
	//				}, true);

	//				// view -> table state
	//				element.bind(event, function (evt) {
	//					evt = evt.originalEvent || evt;
	//					if (promise !== null) {
	//						$timeout.cancel(promise);
	//					}

	//					promise = $timeout(function () {
	//						tableCtrl.search(evt.target.value, attr.stBoundSearch || '');
	//						promise = null;
	//					}, throttle);
	//				});
	//			}
	//		};
	//	}]);

	//////////////


})();


;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsIDSearchController', AdvInstitutionsIDSearchController);

	AdvInstitutionsIDSearchController.$inject = ['$scope', '$state', '$stateParams', 'AdvInstitutionsService', 'StatesService', '$timeout', 'AdvBranchesService', 'HistoryService'];

	function AdvInstitutionsIDSearchController($scope, $state, $stateParams, AdvInstitutionsService, StatesService, $timeout, AdvBranchesService, HistoryService) {

		$scope.dataNotFound = false;


		        $scope.SearchRSSDSubmit = function () {

            if ($scope.lookupCriteria.fdic != null && $scope.lookupCriteria.fdic != "") {
                AdvInstitutionsService.getRSSDIdbyFDIC($scope.lookupCriteria.fdic).then(function (result) {
                    if (result != 0) {
                        $scope.rssd = result;
                        var data = {
                            rssd: $scope.rssd
                        };

                        $state.go('^.summary.details', data);
                    } else {
                        //$scope.dataNotFound = true;
                        var data = {
                            RSSDId: null,
                            FDICCertNum: $scope.lookupCriteria.fdic,
                            OrgName:  null,
                            county:  null,
                            stateId:  null,
                            cityName:   null,
                        };

                        
                            
                            HistoryService
                                .getHistorybyInst(data.RSSDId, data.FDICCertNum, data.OrgName, data.stateId, data.county, data.cityName)
                                .then(function (data) {
                                    if (data) {
                                        if (data.length == 1) {
                                            goToInstitutionDetails(data);
                                        }
                                        else {
                                            $state.go('^.summary.details', { fdic: $scope.lookupCriteria.fdic, rssd: '', fdicNotFound: true});
                                        }
                                    }
                                });
                        

                         
                    }
                });
            }
            if ($scope.lookupCriteria.rssd != null) {
                $scope.rssd = $scope.lookupCriteria.rssd;
                var data = {
                    rssd: $scope.rssd
                };

                $state.go('^.summary.details', data);
            }

        };


        function goToInstitutionDetails(result) {

            var rssdId = result[0].rssdId;
            var data = { rssdId: rssdId };


            if (result[0].isActiveOrg)
                $state.go('root.adv.institutions.summary.history', { rssd: rssdId });
            else
                $state.go('root.adv.history.insthistory', data);
        }


        $scope.SearchBranchSubmit = function () {
            var data = {
                cassidiId: $scope.lookupCriteria.cassidiId,
                firmatId: $scope.lookupCriteria.firmatBranchId,
                uninumber: $scope.lookupCriteria.uninumber,
                branchRssdId: $scope.lookupCriteria.branchRssdId
            };
            AdvBranchesService.getBranchId(data).then(function (result) {
                if (result != 0) {
                    $scope.branchId = result;
                    var id = {
                        branchId: $scope.branchId
                    };

                    $state.go('^.branch.details', id);
                } else {
                    $scope.dataNotFound = true;
                }
            });

        };


        activate();

        function activate() {
            

        }
    }
})();


;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsListController', AdvInstitutionsListController);

    AdvInstitutionsListController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants'];

    function AdvInstitutionsListController($scope, $state, $stateParams, $timeout, $templateCache, AdvInstitutionsService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants) {
        $scope.instData = [];
        $scope.instDataReady = false;


        $scope.totalInstItems = 0;
        $scope.instItemsPerPage = 50;
        $scope.currentInstPage = 1;
        $scope.instPageCount = function () {
            return Math.ceil($scope.instData.length / $scope.instItemsPerPage);
        };


        activate();

        function activate() {
            $timeout(function () {
                $('[id="count"]')[0].focus();

            }, 750);

            window.scrollTo(0, 0);

            var params = {
                name: $stateParams.name,
                rssd: $stateParams.rssd,
                fdic: $stateParams.fdic,
                marketNumber: $stateParams.marketNumber,
                stateId: $stateParams.state,
                countyId: $stateParams.county,
                cityId: $stateParams.city,
                zip: $stateParams.zip,
            };

            AdvInstitutionsService.getInstitutionsSearchData(params).then(function (result) {
                $scope.instData = result;
                var getTophold = false;
                var getInstitution = false;
                if (result.length == 1) {
                    if (result[0].rssdId == result[0].parentId) {
                        getTophold = true;
                    }
                    else {
                        getInstitution = true;
                    }
                    var data = {
                        rssd: result[0].rssdId,
                        getTophold: getTophold,
                        getInstitution: getInstitution

                    };

                    $state.go('^.summary.details', data);
                }
                else {
                    $scope.totalInstItems = $scope.instData.length;
                    $scope.instDataPages = _.chunk($scope.instData, $scope.instItemsPerPage);
                    $scope.instDataReady = true;
                }


            });
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvInstitutionsMergeIntoCUController', AdvInstitutionsMergeIntoCUController);

    AdvInstitutionsMergeIntoCUController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', '$uibModal', 'toastr', 'uibDateParser', '$timeout', 'AdvBranchesService', 'AdvMarketsService', 'Dialogger', 'AdvPendingService'];

    function AdvInstitutionsMergeIntoCUController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, $uibModal, toastr, uibDateParser, $timeout, AdvBranchesService, AdvMarketsService, Dialogger, AdvPendingService) {
        $scope.instData = [];
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
        $scope.criteria = {};
        $scope.criteria.packetId = null;
        $scope.showPendingTransactions = false;
        $scope.runDate = new Date();
        $scope.pendingReady = true;
        $scope.txnIds = [];
        $scope.instType;
        $scope.isWorking = false;
        $scope.nonSurvivorRssd = null;
        $scope.survivorRssd = null;
        $scope.creditUnion = null;
        $scope.nonSurvivorInst = null;
        $scope.nonSurvivorBranches = [];

        //pending transaction stuff

        $scope.toggle = function (id, rssdid, memo, selectedPend) {
            //$scope.txnIds = [];
            var txnIdPos = $scope.txnIds.indexOf(id);
            if (txnIdPos < 0) {
                $scope.txnIds.push(id);  // its not already there, add it
            }
            else {
                // It is already there so we must be unchecking the box. Remove the transaction id 
                $scope.txnIds.splice(txnIdPos, 1);
            }

            $scope.criteria.pendingtransactionRSSDID = rssdid;
            $scope.criteria.pendingtransactionmemo = memo;
            $scope.criteria.selectedPend = selectedPend;
        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };

        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = [];
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

            var d = new Date();

            if ($rootScope.FeatureToggles.ChangePacketIntegration && (!$scope.criteria.packetId || isNaN($scope.criteria.packetId))) {
                toastr.error("You must select a Firma change record packet!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if (!$scope.nonSurvivorRssd) {
                toastr.error("Non-Survivor RSSDID must be entered!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.SurvRSSD) {
                toastr.error("Survivor RSSDID must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }
            if ($scope.contProcessing) {
                var confirmDialog = Dialogger.confirm("WARNING: This action CANNOT be undone. You are about to permanently remove an institution and make it part of a Credit Union. Are you sure that you want to continue? <br /><br />Click OK to continue, Cancel to stop.");
                confirmDialog.then(function (confirmed) {
                    if (confirmed) {
                        processrequestMergeInto();
                    }
                });                
            }
        };

        $scope.populateSurvivorInfo = function () {
            AdvInstitutionsService
                .getAltInstitutionData({ rssdId: $scope.criteria.SurvRSSD, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                .then(function (result) {
                    if (result && result != null) {
                        $scope.creditUnion = result.definition;
                    }
                });
        }


        $scope.displayTotals = function () {
            var nonsurv = 0;
            var surv = 0;

            if ($scope.nonrssdid) {
                angular.forEach($scope.nonrssdid, function (value, index) {
                    nonsurv = nonsurv + value.definition.totalBranchDeposits
                })
            }

            if ($scope.creditUnion) {
                surv = $scope.creditUnion.totalBranchDeposits;
            }
            return nonsurv + surv;
        }

        $scope.makeInitialCap = function (wordToCap) {
            if (!wordToCap || wordToCap == '') { return '';}
            return wordToCap.substr(0, 1).toUpperCase() + wordToCap.substr(1).toLowerCase();
        }


        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');

            popupWin.document.close();
        }        

        function processrequestMergeInto() {
            var instMegeIntoinstInfo = {
                instRssd: $scope.nonSurvivorRssd,
                cuRssd: $scope.creditUnion.rssdId,
                transactionDate: $scope.criteria.historyTransactionDate,
                transDateType: 2,
                firmaPacketId: $scope.criteria.packetId
            }

            $scope.isWorking = true;
            AdvInstitutionsService.postInstMergeIntoCu(instMegeIntoinstInfo)
                .then(function (result) {
                    if (!result.errorFlag) {
                        $scope.displayConfirmation = true;
                        $scope.instDataReady = false;
                        $scope.Instchanged = true;
                        $scope.isWorking = false;

                        if (result.messageTextItems.length > 0) {
                            for (var i = 0; i < result.messageTextItems.length; i++) {
                                toastr.info('Successfully merged!');                                
                            }
                        }

                    }
                    else {
                        if (result.messageTextItems.length > 0) {
                            for (var i = 0; i < result.messageTextItems.length; i++) {
                                toastr.error(result.messageTextItems[i]);
                            }
                        }
                        $scope.isWorking = false;
                    }
                });
        }

        $scope.cancel = function () {
            $scope.$dismiss();
            $state.reload();
        };

        activate();

        function activate() {       
            $scope.nonSurvivorRssd = $state.params.rssd;

            AdvInstitutionsService
                .getInstitutionData({ rssdId: $scope.nonSurvivorRssd, getDetail: true, getBranches: true, getOperatingMarkets: false, getHistory: false })
                .then(function (result) {
                    if (result && result != null) {
                        $scope.nonSurvivorInst = result.definition;
                        $scope.nonSurvivorBranches = result.branches;
                        $scope.instType = $scope.nonSurvivorInst.class == 'BANK' ? 'Bank' : 'Thrift';
                    }
                });

            if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
                $scope.criteria.packetId = -1;
            }

            //move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                var fld = $('[id="historyTransactionDate _input"]')
                if (fld.length > 0) { fld[0].focus(); }
            }, 750);

            window.scrollTo(0, 0);
                        
            //populated the screen correctly
            $scope.instDataReady = true;
            $scope.Instchanged = false;
        }
    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsMergeIntoInstController', AdvInstitutionsMergeIntoInstController);

    AdvInstitutionsMergeIntoInstController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', '$uibModal', 'toastr', 'uibDateParser', '$timeout', 'AdvBranchesService', 'AdvMarketsService', 'Dialogger', 'AdvPendingService'];

    function AdvInstitutionsMergeIntoInstController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, $uibModal, toastr, uibDateParser, $timeout, AdvBranchesService, AdvMarketsService, Dialogger, AdvPendingService) {
        $scope.instData = [];
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
		$scope.criteria = {};
		$scope.criteria.packetId = null;
        $scope.showPendingTransactions = false;
        $scope.runDate = new Date();
        $scope.pendingReady = true;
        $scope.txnIds = [];
		$scope.instType;
		$scope.isWorking = false;

        //pending transaction stuff


        $scope.toggle = function (id, rssdid, memo, selectedPend) {
            //$scope.txnIds = [];
            var txnIdPos = $scope.txnIds.indexOf(id);
            if (txnIdPos < 0) {
                $scope.txnIds.push(id);  // its not already there, add it
            }
            else {
                // It is already there so we must be unchecking the box. Remove the transaction id 
                $scope.txnIds.splice(txnIdPos, 1);
            }

            $scope.criteria.pendingtransactionRSSDID = rssdid;
            $scope.criteria.pendingtransactionmemo = memo;
            $scope.criteria.selectedPend = selectedPend;
        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };

        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = [];
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

        $scope.getRSSDID = function () {
            var data =
            {
                survivorRssdId: $scope.criteria.SurvRSSD
            }
            $scope.pendingReady = false;
            AdvInstitutionsService.getPendingByRssdId(data).then(function (result) {
                if (result) {
                    if (result.length != 0) {
                        $scope.tophold = result;
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = true;
                    }
                    else {
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = false;
                    }
                }
                else {
                    $scope.pendingReady = true;
                    $scope.showPendingTransactions = false;
                }
                $scope.pending = true;
            });

        };
		$scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

			var d = new Date();

			if ($rootScope.FeatureToggles.ChangePacketIntegration && (!$scope.criteria.packetId || isNaN($scope.criteria.packetId))) {
				toastr.error("You must select a Firma change record packet!");
				$scope.contProcessing = false;
			}

            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }
            if ($scope.contProcessing)
            {
                if ($scope.mode == 'mergeintoBank' || $scope.mode == 'mergeintoThrift')
                {
                    processrequestMergeInto();
                }
                else if ($scope.mode == 'failedMergeintoBank' || $scope.mode == 'failedMergeintoThrift')
                {
                    processrequestFailedInstDepositPayoff();
                }
                
            }
        };

        $scope.populateSurvivorInfo = function () {
            AdvInstitutionsService
                          .getInstitutionData({ rssdId: $scope.criteria.SurvRSSD, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                          .then(function (result) {
                              if (result && result != null) {
                                  $scope.survivingrssd = result.definition;
                                  $scope.getRSSDID();
                              }
                          });
        }


        $scope.displayTotals = function ()
        {
            var nonsurv = 0;
            var surv = 0;

            if ($scope.nonrssdid)
            {
                angular.forEach($scope.nonrssdid, function (value, index) {
                    nonsurv = nonsurv + value.definition.totalBranchDeposits
                })
            }

            if ($scope.survivingrssd) {
                surv = $scope.survivingrssd.totalBranchDeposits;
            }
            return nonsurv + surv;
        }
       

        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
			popupWin.document.open();			
			popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
			
            popupWin.document.close();
        }

        function processrequestFailedInstDepositPayoff() {

            var instobj = {
                rssdIdList: $scope.survivingrssd.rssdId
			}
			$scope.isWorking = true;

            AdvInstitutionsService.getInstitutionListForMulRSSDID(instobj).then(function (result) {
				$scope.isWorking = false;
				if (result && result != null) {
                    if (!result.errorFlag) {
                        //should only be one
                        $scope.failedinst = result.instList[0];
                    }
                }
            });
          

            var instFailedIntoinstInfo = {
                failedSurvivorRssdID: $scope.survivingrssd.rssdId,
                transDate: $scope.criteria.historyTransactionDate,
				transType: 2,
				firmaPacketId: $scope.criteria.packetId
            }

            AdvInstitutionsService.postInstFailed(instFailedIntoinstInfo)
             .then(function (result) {
                 if (!result.errorFlag) {
                     $scope.displayConfirmation = true;
                     $scope.instDataReady = false;
                     $scope.Instchanged = true;

                     if (result.messageTextItems.length > 0) {
                         for (var i = 0; i < result.messageTextItems.length; i++) {
                             toastr.info(result.messageTextItems[i]);
                         }
                     }

                 }
                 else {
                     if (result.messageTextItems.length > 0) {
                         for (var i = 0; i < result.messageTextItems.length; i++) {
                             toastr.error(result.messageTextItems[i]);
                         }
                     }
                 }
             });


        }

        function processrequestMergeInto() {

            //for the print confirmation we need to load the inst that we just entered in
            //look up the inst details 
            //need to look this up before the merge
            var instobj = {
                rssdIdList: $scope.criteria.nonSurvRSSD
            }
            AdvInstitutionsService.getInstitutionListForMulRSSDID(instobj).then(function (result) {
                if (result && result != null) {
                    if (!result.errorFlag) {
                        $scope.nonrssdid = result.instList;
                    }
                }
            });


            //var nonSurvivorList = [];
            var nonSurvivorList = $scope.criteria.nonSurvRSSD.toString().split(',');

            var instMegeIntoinstInfo = {
                nonSurvivorRssdID: nonSurvivorList,
                survivorRssdID: $scope.survivingrssd.rssdId,
                transDate: $scope.criteria.historyTransactionDate,
				transType: 2,
				firmaPacketId: $scope.criteria.packetId
            }

			$scope.isWorking = true;
            AdvInstitutionsService.postInstMergeIntoInst(instMegeIntoinstInfo)
             .then(function (result) {
                 if (!result.errorFlag) {
                     $scope.displayConfirmation = true;
                     $scope.instDataReady = false;
                     $scope.Instchanged = true;
					 $scope.isWorking = false;

                     if (result.messageTextItems.length > 0) {
                         for (var i = 0; i < result.messageTextItems.length; i++) {
                             toastr.info('Successfully merged!');
                             if ($scope.txnIds) {
                                 AdvPendingService.getDeletedTransactions($scope.txnIds.join(',')).then(function (result) {
                                     //clear out items
                                     toastr.success('Successfully removed pending transaction!');

                                 });

                             }
                         }
                     }
                    
                 }
                 else {
                     if (result.messageTextItems.length > 0) {
                         for (var i = 0; i < result.messageTextItems.length; i++) {
                             toastr.error(result.messageTextItems[i]);
                         }
					 }
					 $scope.isWorking = false;
                 }
             });
        }

     

        $scope.cancel = function () {
            $scope.$dismiss();
            $state.reload();
        };



        activate();

        function activate() {
			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;		}


			//move to the top of the screen and set focus on the RSSDID
			$timeout(function () {
				var fld = $('[id="historyTransactionDate _input"]')
				if (fld.length > 0) { fld[0].focus(); }
            }, 750);

            window.scrollTo(0, 0);
            var rssd = '';


            //set the nonSurvRSSDID
            $scope.criteria.nonSurvRSSD = '';

            if ($state.params.MergedRSSDID) {
                rssd = $state.params.MergedRSSDID;
            }
            else {
                rssd = $state.params.rssd;
            }

            $scope.criteria.nonSurvRSSD = rssd;


            if ($state.params.mode == 'failedMergeintoThrift' || $state.params.mode == 'failedMergeintoBank')
            {
                AdvInstitutionsService
                           .getInstitutionData({ rssdId: rssd, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                           .then(function (result) {
                               if (result && result != null) {
                                   $scope.survivingrssd = result.definition;
                                   $scope.InstType = $scope.survivingrssd.class == 'BANK' ? 'Bank' : 'Thrift';

                                   if ($state.params.mode == 'failedMergeintoBank') {
                                       $scope.pageTitle = $scope.InstType + " Failed  - Depositor Payoff";
                                       $scope.mode = $state.params.mode;
                                       $scope.surviveMode = 'Bank';
                                       $scope.nonsurviveMode = 'Bank';
                                   }
                                    else if ($state.params.mode == 'failedMergeintoThrift') {
                                       $scope.pageTitle = $scope.InstType + " Failed - Depositor Payoff";
                                       $scope.mode = $state.params.mode;
                                       $scope.surviveMode = 'Thrift';
                                       $scope.nonsurviveMode = 'Bank';
                               }

                               }
                           });
            }
            else
            {
                //$scope.criteria.nonSurvRSSD = $state.params.MergedRSSDID.toString();

                AdvInstitutionsService
                .getInstitutionData({ rssdId: rssd, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                           .then(function (result) {
                               if (result && result != null) {
                                   $scope.nonsurvivingrssd = result.definition;
                                   $scope.instType = $scope.nonsurvivingrssd.class == 'BANK' ? 'Bank' : 'Thrift';

                                   if ($state.params.mode == 'mergeintoBank') {
                                       $scope.pageTitle = $scope.instType + " Merges Into Existing Bank";
                                       $scope.mode = $state.params.mode;
                                       $scope.surviveMode = 'Bank';
                                       $scope.nonsurviveMode = 'Bank';
                                   }
                                   else if ($state.params.mode == 'mergeintoThrift') {
                                       $scope.pageTitle = $scope.instType + " Merges Into Existing Thrift";
                                       $scope.mode = $state.params.mode;
                                       $scope.surviveMode = 'Thrift';
                                       $scope.nonsurviveMode = 'Bank';
                                   }
                                   else if ($state.params.mode == 'mergeintoCreditUnion') {
                                       $scope.pageTitle = $scope.instType + " Merges Into Existing Credit Union";
                                       $scope.mode = $state.params.mode;
                                       $scope.surviveMode = 'CU';
                                       $scope.nonsurviveMode = 'Bank';
                                   }

                               }
                           });


                

            }
            //we need to populate the screen
           
            
           
            

            
                
            //populated the screen correctly
            $scope.instDataReady = true;
            $scope.Instchanged = false;


			
            










        }

    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsSearchController', AdvInstitutionsSearchController);

    AdvInstitutionsSearchController.$inject = ['$scope', '$state', 'AdvInstitutionsService', 'StatesService', 'AdvMarketsService', 'toastr']

    function AdvInstitutionsSearchController($scope, $state, AdvInstitutionsService, StatesService, AdvMarketsService, toastr) {
        $scope.tableDisplay = "byTopholds";
        $scope.customMarkets;

        $scope.SearchOrgSubmit = function () {
            $scope.contProcessing = true;

            var cityId = null;
            if ($scope.criteria.internationalCity != null) {
                cityId = $scope.criteria.internationalCity.cityId;
            }
            else {
                cityId = $scope.criteria.city ? $scope.criteria.city.cityId : null;
            }

            //if market is entered make sure it only has one
            if ($scope.criteria.marketNumber != null) {
                if (($scope.criteria.marketNumber.toString().indexOf(',') > -1))
                    {
                    toastr.error("You cannot enter multiple Market Numbers!");
                    $scope.contProcessing = false;
                    }
            }
            if ($scope.contProcessing == true)
            {
                var data = {
                    name: $scope.criteria.name,
                    marketNumber: $scope.criteria.marketNumber,
                    state: $scope.criteria.state ? $scope.criteria.state.stateId : null,
                    county: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                    city: cityId,
                    zip: $scope.criteria.zip,
                    sdfCodeId: $scope.criteria.sdfCode,
                    customMarket: $scope.criteria.customMarket

                };
                if ($scope.criteria.searchType == "branch") {
                    $state.go('^.branchReportByArea', data);
                }
                else {
                    $state.go('^.list', data);
                }

            }
            

        };


       
        $scope.SearchRSSDSubmit = function () {

            if ($scope.criteria.fdic != null && $scope.criteria.fdic != "") {
                AdvInstitutionsService.getRSSDIdbyFDIC($scope.criteria.fdic).then(function (result) {
                    $scope.rssd = result;
                    var data = {
                        rssd: $scope.rssd
                    };

                    $state.go('^.summary.details', data);
                });
            }
            if ($scope.criteria.rssd != null) {
                $scope.rssd = $scope.criteria.rssd;
                var data = {
                    rssd: $scope.rssd
                };

                $state.go('^.summary.details', data);
            }

        };

        $scope.SearchBranchSubmit = function () {
            var data = {
                cassidiId: $scope.criteria.cassidiId,
                firmatBranchId: $scope.criteria.firmatBranchId,
                uninumber: $scope.criteria.uninumber,
                branchRssdId: $scope.criteria.branchRssdId
            };
            AdvInstitutionsService.getBranchId(data).then(function (result) {
                $scope.branchId = result;
                var id = {
                    branchId: $scope.branchId
                };

                $state.go('^.branch', id);
            });

        };



        activate();

        function activate() {
            AdvMarketsService.GetCustomMarkets().then(function (result) {
                $scope.customMarkets = result;
            });

        }
    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('AdvInstitutionsService', AdvInstitutionsService);

    AdvInstitutionsService.$inject = ['$http', '$log', '$uibModal', 'toastr', '$state'];

    function AdvInstitutionsService($http, $log, $uibModal, toastr, $state) {
        var service = {
            getInstitutionsSearchData: getInstitutionsSearchData,
            getNonHHIInstitutionsSearchData: getNonHHIInstitutionsSearchData,
            getInstitutionData: getInstitutionData,
            getInstitutionHistoryData: getInstitutionHistoryData,
            getEditInstitutionData: getEditInstitutionData,
            getEditTopholdData: getEditTopholdData,
            getRSSDIdbyFDIC: getRSSDIdbyFDIC,
            getCustomMarkets: getCustomMarkets,
            getSDFCodes: getSDFCodes,
            getGetHistory: getGetHistory,
            postupdateHistory: postupdateHistory,
            postDelHistory: postDelHistory,
            getFHCorg: getFHCorg,
            addOrEditInstitution: addOrEditInstitution,
            addOrEditTophold: addOrEditTophold,
            postInstitution: postInstitution,
            postTophold: postTophold,
            postupdateInstitution: postupdateInstitution,
            postupdateBranch: postupdateBranch,
            postupdateTophold: postupdateTophold,
            postaddInstitution: postaddInstitution,
            postaddTophold: postaddTophold,
            postCloseTopHoldbyRSSDID: postCloseTopHoldbyRSSDID,
            postMergeTopHoldbyRSSDID: postMergeTopHoldbyRSSDID,
            getStateDeposits: getStateDeposits,
            getHHICILoanAnalysis: getHHICILoanAnalysis,
            getDistrictByLocation: getDistrictByLocation,
            TopholdCeases: TopholdCeases,
            TopholdAcquired: TopholdAcquired,
            TopholdAcquiredInst: TopholdAcquiredInst,
            getmsabyDistrictID: getmsabyDistrictID,
            addOrEditBranch: addOrEditBranch,
            opensoldBranchtoBankorThrift: opensoldBranchtoBankorThrift,
            postInstAcquiredByTopHold: postInstAcquiredByTopHold,            
            postAcquiredByTophold: postAcquiredByTophold,
            InstitutionBuysBranch: InstitutionBuysBranch,
            postcloseInstitution: postcloseInstitution,
			getPendingByRssdId: getPendingByRssdId,
			getPendingDeNovo: getPendingDeNovo,
            openMergeInfoBankorThrift: openMergeInfoBankorThrift,
            postInstMergeIntoInst: postInstMergeIntoInst,
            getInstitutionListForMulRSSDID: getInstitutionListForMulRSSDID,
            postInstFailed: postInstFailed,
            postInsFailedtMergeIntoInst: postInsFailedtMergeIntoInst,
            openFailureDepPayoffBankorThrift: openFailureDepPayoffBankorThrift,
            hasBankOrBHC: hasBankOrBHC,
            openInstToUnAssociates: openInstToUnAssociates,
            postConvertControlledInstitutionToIndependent: postConvertControlledInstitutionToIndependent,
			isActiveRSSDId: isActiveRSSDId,
			getRSSDIdFromPartial: getRSSDIdFromPartial,
			getOrgNameFromPartial: getOrgNameFromPartial,
            getUnlinkedChangePackets: getUnlinkedChangePackets,
            getRegulators: getRegulators,
			getOrgEntityTypeCodes: getOrgEntityTypeCodes,
            getFindFdicCandidates: getFindFdicCandidates,
            getFindOpenClosedBranches: getFindOpenClosedBranches,
            getIsCURssd: getIsCURssd,
            getAltInstitutionData: getAltInstitutionData,
            postInstMergeIntoCu: postInstMergeIntoCu,
            openMergeInfoCU: openMergeInfoCU,
            getTopholdBusStateCount: getTopholdBusStateCount
         };

        return service;
        ////////////////

		function getFindFdicCandidates(branchId, fdicCert, stateFipsId) {
            if (branchId && branchId > 0) {

                return $http.get('/api/advInstitutions/FindFdicCandidates', { params: { branchId: branchId } })
                    .then(function Success(result) {
                        return result.data;
                    }, function Failure(result) {
                        $log.error("Error searching for FDIC branch data", result);
                    });
            }
            else {

                return $http.get('/api/advInstitutions/FindFdicCandidates', { params: { branchId: -1, fdicCert: fdicCert, stateFipsId: stateFipsId } })
                    .then(function Success(result) {
                        return result.data;
                    }, function Failure(result) {
                        $log.error("Error searching for FDIC branch data", result);
                    });
            }
        }

        function getFindOpenClosedBranches(startDate, endDate) {
                return $http.get('/api/advInstitutions/FindOpenClosedBranches', { params: { startDate: startDate, endDate: endDate } })
                    .then(function Success(result) {
                        return result.data;
                    }, function Failure(result) {
                        $log.error("Error searching for FDIC closed branches in CASSIDI", result);
                    });        
        }


		function getRSSDIdFromPartial(partRssd, maxReturnCount, orgTypeLetterCode, useAltOrgs) {
			if (isNaN(maxReturnCount)) {
				maxReturnCount = 0;
            }

            if (typeof useAltOrgs == "undefined" || useAltOrgs != true) {
                useAltOrgs = false;
            }

            return $http.get('/api/advInstitutions/GetRSSDIdFromPartial', { params: { partialRSSDId: partRssd, maxCount: maxReturnCount, orgTypeLetterCode: orgTypeLetterCode, useAltOrgs: useAltOrgs} })
				.then(function Success(result) {
					var returnData = result.data;
					if (returnData.indexOf(partRssd) == -1) { returnData.unshift(partRssd); } // if typed val not in list, add it to the top to allow enter key
					return returnData;
				}, function Failure(result) {
					$log.error("Error returning RSSDIds", result);
				});
		}

		function getOrgNameFromPartial(partialName, maxReturnCount, historic) {
			if (isNaN(maxReturnCount)) {
				maxReturnCount = 0;
			}

			var doHistoricSearch = false;
			if (historic) {
				doHistoricSearch  = true;
			}


			return $http.get('/api/advInstitutions/OrgNamesFromPartial', { params: { partialName: partialName, maxCount: maxReturnCount, historicSearch: doHistoricSearch  } })
				.then(function Success(result) {
					var returnData = result.data;
					if (returnData.indexOf(partialName) == -1) { returnData.unshift(partialName); } // if typed val not in list, add it to the top to allow enter key
					return returnData;
				}, function Failure(result) {
					$log.error("Error returning organization names", result);
				});
		}

        function getInstitutionsSearchData(data) {
            return $http.get('/api/advinstitutions/search', { params: { name: data.name, rssd: data.rssd, fdic: data.fdic, marketNumber: data.marketNumber, stateId: data.stateId, countyId: data.countyId, cityId: data.cityId, zip: data.zip, sdfCodeId: data.sdfCodeId, cassidiId: data.cassidiId, firmatBranchId: data.firmatBranchId, uninumber: data.uninumber } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }

        function getNonHHIInstitutionsSearchData(data) {
            return $http.get('/api/advinstitutions/search', { params: {districtId: data.districtId, name: data.name, rssd: data.rssd, fdic: data.fdic, marketNumber: data.marketNumber, stateId: data.stateId, countyId: data.countyId, cityName: data.cityName, zip: data.zip, sdfCodeId: data.sdfCodeId, cassidiId: data.cassidiId, firmatBranchId: data.firmatBranchId, uninumber: data.uninumber, customMarket: data.customMarket, basicNonHHI: true, regulatorId: data.regulatorId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }

        function getInstitutionData(data) {
            return $http.get('/api/advinstitutions/inst-by-id', { params: { rssdId: data.rssdId, getDetail: data.getDetail, getBranches: data.getBranches, getOperatingMarkets: data.getOperatingMarkets, getHistory: data.getHistory } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }
        //                                                                   
        function getAltInstitutionData(data) {
            return $http.get('/api/advinstitutions/altinst-by-id', { params: { rssdId: data.rssdId, getDetail: data.getDetail, getBranches: data.getBranches, getOperatingMarkets: data.getOperatingMarkets } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }

        function getInstitutionHistoryData(data) {
            return $http.get('/api/advinstitutions/Inactive-inst-by-id', { params: { rssdId: data.rssdId} })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }
        function getEditInstitutionData(data) {
            return $http.get('/api/advinstitutions/inst-edit-by-id', { params: { rssdId: data.rssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }

        function getTopholdBusStateCount(rssdId) {
            return $http.get('/api/institutions/num-tophold-states', { params: { rssdId: rssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting tophold business states", result);
                });
        }

        function getRegulators() {
            return $http.get('/api/advinstitutions/inst-regulators')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning regulatory data", result);
                });
        }

        
        function getInstitutionListForMulRSSDID(data) {
            return $http.get('/api/advinstitutions/inst-list-for-multiple-id', { params: { rssdIdList: data.rssdIdList } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }

        function getIsCURssd(rssdId) {
            return $http.get('/api/advinstitutions/get-is-cu-rssd', { params: { rssdId: rssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution search data", result);
                });
        }


        function getEditTopholdData(data) {
            return $http.get('/api/advinstitutions/tophold-edit-by-id', { params: { rssdId: data.rssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning tophold edit data", result);
                });
        }

        function getRSSDIdbyFDIC(data) {
            return $http.get('/api/advinstitutions/rssd-by-fdic', { params: {fdicId: data} })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning rssd data", result);
                });
        }
   
        function getCustomMarkets(data) {
            return $http.get('/api/advinstitutions/get-custom-markets')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning sdf data", result);
                });
        }

        function getSDFCodes(entitytypecode) {
            return $http.get('/api/advinstitutions/sdf-codes', { params: { entitytypecode: entitytypecode } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning sdf data", result);
                });
		}

		function getOrgEntityTypeCodes() {
			return $http.get('/api/advinstitutions/get-org-entityTypes')
				.then(function Success(result) {
					return result.data;
				}, function Failure(result) {
					$log.error("Error returning org entity type list", result);
				});
		}  
     
        function getGetHistory(structHistoryMemoId) {

            return $http.get('/api/history/get-history', { params: { structHistoryMemoId: structHistoryMemoId } })
                .then(function Success(result) {
                    //$log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History get History Transaction", result);
                });
        }

        function postupdateHistory(historyData) {
            var data = {
                historyRecord: historyData.historyRecord,
                copyUserMemoToAll: historyData.copyUserMemoToAll,
                transDateType: historyData.transDateType, 
            };
              


            return $http.post('/api/history/edit-history', data)
                .then(function Success(result) {
                    //$log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning History update History Transaction", result);
                });
        }

        function postDelHistory(historyData) {
            var data = {
                structHistoryMemoId: historyData.historyRecord.structureHistoryMemoId,
                cascadeDeleteAllRelated: historyData.cascadeDeleteAllRelated
            };
            //structHistoryMemoId, cascadeDeleteAllRelated

			return $http.post('/api/history/del-history', data)
            .then(function Success(result) {
                //$log.info("sucess" + result.data);
                return result.data;
            }, function Failure(result) {
                $log.error("Error returning History delete History Transaction", result);
            });
		}

		//function postDeleteDeNovoPending(pendingId, fdicCertNum) {
		//	return $http.get('/api/pending/DeletePending', { params: { pendIds: data } })
		//		.then(function Success(result) {
		//			return result.data;
		//		}, function Failure(result) {
		//			$log.error("Error deleting pending transaction data", result);
		//		});
		//}

        function getFHCorg() {
            return $http.get('/api/advinstitutions/get-fhc-org')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning FHC data", result);
                });
        }
 
        function addOrEditInstitution(rssd) {
             $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: false,
                backdrop : 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_institution.html',
                controller: 'AdvInstEditController',
                resolve: {
                    rssdId: function () {
                        return rssd;
                    }
                }
             })
           .result.then(function (result) {
               postTophold(rssdId, result)
               .then(function (data) {

                   if (!data.errorFlag)
                       toastr.success(rssdId ? "Institution was updated" : "Institution was added");
                   else {
                       var errorMessage = [];
                       if (data.messageTextItems.length > 0) {
                           for (var i = 0; i < data.messageTextItems.length; i++) {
                               errorMessage.push(data.messageTextItems[i]);
                           }
                       }
                       toastr.error("There was an unexpected error.", errorMessage.join() || "Please try again or contact support. Sorry about that.");
                   }


               }, function (err) {
                   alert("Sorry. There was an error.");
               });

           }, function () {
               //dismissed
           });
        }

        function addOrEditTophold(rssdId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_tophold.html',
                controller: 'AdvTopholdEditController',
                resolve: {
                    rssdId: function () {
                        return rssdId;
                    }
                }
            })
           .result.then(function (result) {
               postTophold(rssdId, result)
               .then(function (data) {
                    
                   if (!data.errorFlag)
                       toastr.success(rssdId ? "Institution was updated" : "Institution was added");
                   else {
                       var errorMessage = [];
                       if (data.messageTextItems.length > 0) {
                           for (var i = 0; i < data.messageTextItems.length; i++) {
                               errorMessage.push(data.messageTextItems[i]);
                           }
                       }
                       toastr.error("There was an unexpected error.", errorMessage.join() || "Please try again or contact support. Sorry about that.");
                   }


               }, function (err) {
                   alert("Sorry. There was an error.");
               });

           }, function () {
               //dismissed
           });
        }
        function InstCeases(rssdId) {
            alert("not implemented!");
        }

        function TopholdCeases(rssdId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_tophold_ceases.html',
                controller: 'AdvInstitutionsTHCAdminController',
                resolve: {
                    rssdId: function () {
                        return rssdId;
                    }
                }
            });
        }


        function TopholdAcquired(rssdId, mode) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_tophold_acquired.html',
                controller: 'AdvInstitutionsTHCAdminController',
                resolve: {
                    rssdId: function () {return rssdId;},
                    mode: function () {return mode;}
                }
            });
        }


        function TopholdAcquiredInst(TopHoldrssdId, mode, TransactionDate, PacketId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_instSearch_Aquiredby_Tophold.html',
                controller: 'AdvFindInstForAquiringbyTophold',
                resolve: {
                    TopHoldrssdId: function () { return TopHoldrssdId; },
                    mode: function () { return mode; },
                    TransactionDate: function () { return TransactionDate;}
                }
            });
        }


        function addOrEditBranch(branch) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_Branch.html',
                controller: 'AdvInstitutionsEditBranchController',
                resolve: {
                    branchID: function () {
                        return branch;
                    }
                }
            })
           .result.then(function (result) {
              //need to do something here.  

           }, function () {
               //dismissed
           });
        }

        
        function opensoldBranchtoBankorThrift(branch) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_instSold.html',
                controller: 'AdvInstitutionsSoldBranchController',
                resolve: {
                    branchID: function () {
                        return branch;
                    }
                }
            })
           .result.then(function (result) {
               //need to do something here.  

           }, function () {
               //dismissed
           });
        }

        
        function openInstToUnAssociates(rssdId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_instUnAssoicate.html',
                controller: 'AdvInstitutionsUnAssoicateController',
                resolve: {
                    rssdId: function () {
                        return rssdId;
                    }
                }
            })
           .result.then(function (result) {
               //need to do something here.  

           }, function () {
               //dismissed
           });
        }


        function openMergeInfoBankorThrift(rssdId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_instMergeInto.html',
                controller: 'AdvInstitutionsMergeIntoInstController',
                resolve: {
                    rssdId: function () {
                        return rssdId;
                    }
                }
            })
           .result.then(function (result) {
               //need to do something here.  

           }, function () {
               //dismissed
           });
        }

        function openMergeInfoCU(rssdId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_instMergeIntoCU.html',
                controller: 'AdvInstitutionsMergeIntoCUController',
                resolve: {
                    rssdId: function () {
                        return rssdId;
                    }
                }
            })
                .result.then(function (result) {
                    //need to do something here.  

                }, function () {
                    //dismissed
                });
        }

        
        function openFailureDepPayoffBankorThrift(rssdId) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_instfailedDepositPayoff.html',
                controller: 'AdvInstitutionBankFailureController',
                resolve: {
                    rssdId: function () {
                        return rssdId;
                    }
                }
            })
           .result.then(function (result) {
               //need to do something here.  

           }, function () {
               //dismissed
           });
        }

        function postInstitution(id, inst) {
            return id ? postupdateInstitution(inst) : postaddInstitution(inst);
        }

        function postTophold(id, inst) {
            return id ? postupdateTophold(inst) : postaddTophold(inst);
        }


        function postcloseInstitution(instdata) {
            var data = {
                instRecord: instdata.instRecord,
                cascadeToHomeBranch: instdata.cascadeToHomeBranch,
                bypassHistory: instdata.bypassHistory,
                transDate: instdata.transDate,
				transType: instdata.transType,
				firmaPacketId: instdata.firmaPacketId
            };
            
            return $http.post('/api/advinstitutions/close-institution', data)
            .then(function Success(result) {
                return result.data;
            }, function Failure(result) {
                $log.error("Error saving institution data", result);
            });
           
           
            
        }

        function postupdateInstitution(instdata, mode) {
            var data = {
                instRecord: instdata.instRecord,
                cascadeToHomeBranch: instdata.cascadeToHomeBranch,
                bypassHistory: instdata.bypassHistory,
                transDate: instdata.transDate,
				transType: instdata.transType,
				firmaPacketId: instdata.firmaPacketId
            };

            return $http.post('/api/advinstitutions/edit-institution', data)
            .then(function Success(result) {
                return result.data;
            }, function Failure(result) {
                $log.error("Error saving institution data", result);
            });


        }


        function postupdateTophold(thData) {
            var data = {
                topholdRecord: thData.tophold,
                bypassHistory: thData.bypassHistory,
                transDate: thData.transDate,
				transType: thData.transType,
				changePacketId: thData.firmaPacketId
            };
            return $http.post('/api/advinstitutions/edit-tophold', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error saving tophold data", result);
                });
        }

        function postaddInstitution(instdata) {
            var data = {
                        instRecord: instdata.instRecord,
                        cascadeToHomeBranch: instdata.cascadeToHomeBranch,
                        bypassHistory: instdata.bypassHistory,
                        transDate: instdata.transDate,
						transType: instdata.transType,
						firmaPacketId: instdata.firmaPacketId
            };
            return $http.post('/api/advinstitutions/add-institution', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error adding institution data", result);
                });
        }

        function postupdateBranch(branchData) {
            var data = {
                branchRecord: branchData.branchRecord,
                bypassHistory: branchData.bypassHistory,
                transDate: branchData.transDate,
                transType: branchData.TransactionDateType
            };
            return $http.post('/api/advinstitutions/edit-branch', data);
        }

        function postaddTophold(thData) {
            var data = {
                topholdRecord: thData.tophold,
                bypassHistory: thData.bypassHistory,
                transDate: thData.transDate,
                transType: thData.transType,
				transactionIds: thData.transactionId,
				changePacketId: thData.changePacketId
            };
            return $http.post('/api/advinstitutions/add-tophold', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error adding tophold data", result);
                });
        }

        ////long topholdRSSdId, DateTime transactionDate, TransactionDateType transDateType
        //function postCloseTopHoldbyRSSDID(data) {
        //    $log.info('RSSDID' + data.rSSDId);
        //    return $http.post('/api/advinstitutions/close-tophold-by-rssdid', data)
        //        .then(function Success(result) {
        //            return result.data;
        //        }, function Failure(result) {
        //            $log.error("Error closing the Tophold data", result);
        //        });
        //}


        function postMergeTopHoldbyRSSDID(data) {

            return $http.post('/api/advinstitutions/merge-tophold-by-rssdid', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error merging THC data", result);
                });
        }



        function getCustomMarkets(data) {
            return $http.get('/api/advinstitutions/get-custom-markets')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning sdf data", result);
                });
        }

     
     
        //long topholdRSSdId, DateTime transactionDate, TransactionDateType transDateType
        function postCloseTopHoldbyRSSDID(data) {
            //$log.info('RSSDID' + data.rSSDId);
            return $http.post('/api/advinstitutions/close-tophold-by-rssdid', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error closing the Tophold data", result);
                });
        }

        function postInstAcquiredByTopHold(data) {
            //$log.info('RSSDID' + data.rSSDId);
            return $http.post('/api/advinstitutions/inst-acquire-by-tophold', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error inst acquired by Tophold", result);
                });
        }


       


        function getStateDeposits(data) {

            return $http.post('api/advinstitutions/state-deposits', data)
                .then(function Success(result) {
                    return result;
                }, function Failure(result) {
                    $log.error("Error gathering States Depsoit data", result);
                });
        }

        function getHHICILoanAnalysis(marketnumber) {

            return $http.get('api/advinstitutions/hhi-c-i-loan-analysis', { params: { marketnumber: marketnumber } })
                .then(function Success(result) {
                    return result;
                }, function Failure(result) {
                    $log.error("Error gathering hhi-c-i-loan-analysis data", result);
                });
        }

        function InstitutionBuysBranch(data) {

            return $http.post('api/advinstitutions/inst-Buys-Branch', data)
                .then(function Success(result) {
                    return result;
                }, function Failure(result) {
                    $log.error("Error saving Institution Buys Branch data", result);
                });
		}

		function getUnlinkedChangePackets(rssdId) {
			return $http.post('api/advinstitutions/UnlinkedChangeRecPackets', { params: { "rssdId": rssdId } })
				.then(function Success(result) {
					return result;
				}, function Failure(result) {
					$log.error("Error getting unlinked change packets", result);
				});			
		}

        

        function getDistrictByLocation(data) {

            return $http.get('api/admin/getDistrictByLocation', { params: { stateFipsId: data.stateFipsId, countyId: data.countyId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error gather District ID", result);
                });
        }

        function getmsabyDistrictID(data)
        {
            return $http.get('api/admin/getMSAbyDistrict',{ params: { districtId: data.districtId , stateId: data.stateId  , countyId: data.countyId } } )
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error gather MSA", result);
                });
        }

        function postAcquiredByTophold(rssdID) {

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'xlg',
                templateUrl: 'AppJs/advanced/institutions/views/_Inst_AquiredBy_Tophold.html',
                controller: 'AdvInstAcquiredByTophold',
                resolve: {
                    rssdID: function () {
                        return rssdID;
                    }
                }
            
            });


        }

        function getPendingByRssdId(data) {
            return $http.get('/api/pending/GetPendingByRssdId', { params: { survivorRssdId: data.survivorRssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning institution pending data", result);
                });
		}


		function getPendingDeNovo(data) {
			return $http.get('/api/pending/GetPendingDeNovo', { params: { FDICCertNum: data } })
				.then(function Success(result) {
					return result;
				}, function Failure(result) {
					$log.error("Error returning de novo pending data", result);
				});
		}


        function postInstMergeIntoInst(data) {

            return $http.post('/api/advinstitutions/inst-merge-into-inst', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error merging inst-merge-into-inst data", result);
                });
        }

        function postInstMergeIntoCu(data) {

            return $http.post('/api/advinstitutions/inst-merge-into-creditunion', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error merging InstMergeIntoCreditUnion data", result);
                });
        }
        
        function postInstFailed(data) {

            return $http.post('/api/advinstitutions/inst-failed-Depositoff', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error merging inst-failed-Depositoff data", result);
                });
        }

        function postInsFailedtMergeIntoInst(data) {
            return $http.post('/api/advinstitutions/inst-failed-merge-into-inst', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error merging inst-failed-merge-into-inst data", result);
                });
        }

        function hasBankOrBHC(data) {

            return $http.post('/api/advinstitutions/has-bank-or-bhc', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting hasBankOrBHC value", result);
                });
        }

        function postConvertControlledInstitutionToIndependent(data) {
            return $http.post('/api/advinstitutions/Convert-Controlled-Institution-To-Independent', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error merging Convert-Controlled-Institution-To-Independent data", result);
                });
        }
        function isActiveRSSDId(data) {

            return $http.post('/api/advinstitutions/is-active-inst', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting Active status value", result);
                });
        }
    }
})();
;
(function () {
    'use strict';
    angular
       .module('app')
       .controller('AdvInstitutionsSoldBranchController', AdvInstitutionsSoldBranchController);
    AdvInstitutionsSoldBranchController.$inject = ['$scope', '$rootScope', '$stateParams', 'toastr', 'AdvInstitutionsService','$uibModal','Dialogger', '$state','$timeout','AdvPendingService'];

	function AdvInstitutionsSoldBranchController($scope, $rootScope, $stateParams, toastr, AdvInstitutionsService, $uibModal, Dialogger, $state, $timeout, AdvPendingService) {
        $scope.branchList = [];
        $scope.criteria = [];
        $scope.sellingData = []
        $scope.criteria.newHeadNumber = null;
        $scope.instData = [];
        $scope.branches = [];
        $scope.definition = [];
        $scope.institutionLoaded = true;
        $scope.instPageSize = 20;
        $scope.newDate = new Date();
        $scope.BranchesSelected = [];
        $scope.displayFacilities = [];
        $scope.criteria.validPurchasingRssdId = false;
        $scope.displayConfirmation = false;
        $scope.processed = false;
        $scope.purchasingData = [];
        $scope.newHeadSelected = false;
        $scope.showTransactionErrorMsg = false;
        $scope.instDataReady = false;
        $scope.Instchanged = false;
        var branchesTo = []
        var getDetail = true;
        var getBranches = false;
        var getOperatingMarkets = false;
        var getHistory = false;
        $scope.contProcessing = true;
		$scope.txnIds = [];
		$scope.criteria.packetId = null;

        activate();

        //pending stuff
        $scope.getRSSDID = function () {
            var data =
            {
                SurvivorRssdId: $scope.criteria.soldRssdId,
                NonSurvivorRssdId: $scope.criteria.purchasingRssdId
            }


            $scope.pendingReady = false;
            AdvPendingService.getPendingTHAcqTH(data).then(function (result) {
                if (result) {
                    if (result.length != 0) {
                        $scope.tophold = result;
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = true;
                    }
                    else {
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = false;
                    }
                }
                else {
                    $scope.pendingReady = true;
                    $scope.showPendingTransactions = false;
                }
                $scope.pending = true;
            });
        };


        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = [];
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

        $scope.toggle = function (id, rssdid, memo, selectedPend) {
            $scope.txnIds = [];
            $scope.txnIds.push(id);

            $scope.criteria.pendingtransactionRSSDID = rssdid;
            $scope.criteria.pendingtransactionmemo = memo;
            $scope.criteria.selectedPend = selectedPend;


        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };


        $scope.$watch('criteria.soldRssdId', function (newValue, oldValue) {
  
                $scope.institutionLoaded = false;
                AdvInstitutionsService.getInstitutionData({ rssdId: newValue, getDetail: true, getBranches: true }).then(function (result) {
                    $scope.instData = result;
                    $scope.branches = result.branches;
                    branchesTo = result.branches;
                    $scope.definition = result.definition;
                    $scope.institutionLoaded = true;
                });

        });
        $scope.$watch('criteria.newHeadNumber', function (newValue,oldValue) {

            if (oldValue != null && newValue == null) {
                for (var i = 0; i < $scope.BranchesSelected.length; i++) {
                    if($scope.BranchesSelected[i].facility == 0)
                    {
                        $scope.BranchesSelected.splice(i, 1);
                        $scope.newHeadSelected = false;
                    }
                }
            }

        });
        $scope.validateValue = function () {
            var newValue = $scope.criteria.purchasingRssdId;
			var hasValError = false;
            AdvInstitutionsService.getInstitutionData({ rssdId: newValue, getDetail: getDetail, getBranches: getBranches, getOperatingMarkets: getOperatingMarkets, getHistory: getHistory }).then(function (result) {
                if (result != null) {
                    if (result.definition != null) {
                        if ($scope.buyer.toUpperCase() == result.definition.class.toUpperCase()) {
                            $scope.purchasingData = result.definition;
                            $scope.criteria.validPurchasingRssdId = true;
                            $scope.getRSSDID();
                        }
                        else {
                            $scope.criteria.purchasingRssdId = null;
                            $scope.criteria.validPurchasingRssdId = false;
							toastr.error("No " + $scope.buyer + " Parent was found with buyer RSSDID " + newValue);
							hasValError = true;
                        }
                    }
                    else {
                        $scope.criteria.purchasingRssdId = null;
						toastr.error("No " + $scope.buyer + " Parent was found with buyer RSSDID " + newValue);
						hasValError = true
                    }
                }
			});

			return !hasValError;
        };


        $scope.saveChanges = function () {
            $scope.contProcessing = true;

			var d = new Date();

			if ($scope.validateValue() == false) {
				$scope.contProcessing = false;
			}

			if ($rootScope.FeatureToggles.ChangePacketIntegration && !$scope.criteria.packetId) {
				toastr.error("Change packet is required!");
				$scope.contProcessing = false;
			}

            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if ($scope.branches.length == 0) {
                toastr.error("The parent doesn't have any Branches to sell!");
                $scope.contProcessing = false;
            }


            if (!$scope.criteria.soldRssdId)
            {
                toastr.error("You must enter a Sold RSSDID!");
               
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.purchasingRssdId) {
                toastr.error("You must enter a Purchase RSSDID!");
               
                $scope.contProcessing = false;
            }


            if ($scope.BranchesSelected.length == 0) {
                toastr.error("Please select branches to be sold!");
                $scope.contProcessing = false;
            }



            if ($scope.contProcessing == true )
            {
                
                var targetBranchNums = getBranchesNums();

                //if we only have 1 branch or we will sell all the branches for the parent then ask if they want to close the bank
                if (targetBranchNums.length == $scope.branches.length) {
                    //  If the number of branches = the number of branches selected
                    Dialogger.confirm('You are selling all of the Branches for a Parent, would you like to also close the parent?', null, true).then(function (result) {
                        $scope.closeParent = result;
                        processChange(targetBranchNums, $scope.closeParent)
                    });


                }
                else {
                    processChange(targetBranchNums, false);
                }
            }
            
               
            //}
        };

        function processChange(targetBranchNums, closeParent)
        {
            var transDateType = 2; // for Sold always Consummation = 2
            var data = {
                targetInstitutionRSSDId: $scope.criteria.soldRssdId,
                targetBranchNums: targetBranchNums,
                buyerRSSDId: $scope.criteria.purchasingRssdId,
                transactionDate: $scope.criteria.historyTransactionDate,
                transDateType: transDateType,
                newHeadOfficeBranchNum: $scope.criteria.newHeadNumber,
				closeParent: closeParent,
				firmaPacketId: $scope.criteria.packetId
            }
            AdvInstitutionsService.InstitutionBuysBranch(data)
              .then(function (result) {
                  if (!result.data.errorFlag) {
                      $scope.newHOBranch = _.find($scope.branches, { facility: $scope.criteria.newHeadNumber });
                      $scope.displayConfirmation = true;
                      $scope.processed = true;
                      $scope.instDataReady = false;
                      $scope.Instchanged = true;
                      $scope.branchNumberList = targetBranchNums;
                      if ($scope.txnIds.length > 0)
                      {
                          AdvPendingService.getDeletedTransactions($scope.txnIds).then(function (result) {
                              toastr.success(result.errorMessage);
                              $scope.showPendingTransactions = false;
                              $log.info(instData);
                              $scope.postcriteria = instData.definition;
                          });
                      }
                      



                  }
                  else {
                      if (result.data.messageTextItems.length > 0) {
                          for (var i = 0; i < result.data.messageTextItems.length; i++) {
                              toastr.error(result.data.messageTextItems[i]);
                             }
                         }
                  }
              });
        }
        $scope.addRemoveBranch = function (branch, branchCnt) {
            
            var idx = $scope.BranchesSelected.indexOf(branch);

            if (idx > -1) {
                $scope.BranchesSelected.splice(idx, 1);
                if (branch.facility == 0) {
                    $scope.newHeadSelected = false;
                }
            }
            else {
                $scope.BranchesSelected.push(branch);

                if (branch.facility == 0) {
                    if ($scope.branches.length != $scope.BranchesSelected.length) {
                        $scope.newHeadSelected = true;

                        var branchS = $scope.BranchesSelected;
                        selectNewHeadBranch(branchesTo, branchS);
                        }
                    }
            }
        }
        function capitalize(s) {
            return s[0].toUpperCase() + s.slice(1);
        }
        function getBranchesNums() {
            var targetBranchNums = [];

            for (var i = 0; i < $scope.BranchesSelected.length; i++) {
                targetBranchNums.push($scope.BranchesSelected[i].facility);
            }

            return targetBranchNums;
        }
       
        function selectNewHeadBranch(branches, BranchesSelected) {
           var modalInstance = $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: false,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_newHeadBranch.html',
                controller: ['$scope', "$uibModalInstance", '$rootScope', 'toastr', function ($scope, $uibModalInstance, $rootScope, toastr) {
                    $scope.branches = branches;
                    $scope.BranchesSelected = BranchesSelected;
                    $scope.criteria = [];
                    $scope.criteria.newBranchNumber = null;
                    var facilityExists = false;

                    $scope.cancel = function () {
                        $scope.branches = null;
                        $scope.BranchesSelected = null;
                        $scope.$dismiss();
                        
                    };
                    $scope.isBranchSelected = function(branch){
                        var value = true;

                        var idx = $scope.BranchesSelected.indexOf(branch);
                        if (idx > -1) {
                            value = false;
                        }

                        return value;
                    };
                    $scope.AddFacilityNumber = function (facility) {
                        $scope.criteria.newBranchNumber = facility;
                    };
                    $scope.submit = function () {
                       
                        for (var i = 0; i < $scope.branches.length; i++) {
                            var id = $scope.branches[i].facility;

                            if (id == $scope.criteria.newBranchNumber) {
                                facilityExists = true;
                                $uibModalInstance.close($scope.criteria.newBranchNumber);
                                break;
                            }
                        }

                        if (!facilityExists) {
                            var wrongFacility = $scope.criteria.newBranchNumber;
                            $scope.criteria.newBranchNumber = null;
                            toastr.error("No branch was found with facility id " + wrongFacility + ", please try again.");
                        }
                       
                    };

                }]
           })
           modalInstance.result.then(function (data) {
               $scope.criteria.newHeadNumber = data;
               if(data == null){
                   for (var i = 0; i < $scope.BranchesSelected.length; i++) {
                       if ($scope.BranchesSelected[i].facility == 0) {
                           $scope.newHeadSelected = false;
                           $scope.BranchesSelected.splice(i, 1);
                       }
                   }

               }
           }, function () {

           });
        }

        $scope.removeSelection = function () {
            $scope.BranchesSelected = [];
        }

        $scope.addAllSelection = function()
        {

            for (var i = 0; i < $scope.branches.length; i++) {
                $scope.BranchesSelected[i] = $scope.branches[i];
                
                }

        }


        $scope.isBranchSelected = function (branch) {
            var value = false;

            var idx = $scope.BranchesSelected.indexOf(branch);
            if (idx > -1) {
                value = true;
            }

            return value;
		}

        $scope.cancel = function () {
            $scope.$dismiss();

		}

        $scope.criteriaValid = function () {
            var returnValue = false;

            if ($scope.BranchesSelected.length > 0 &&
                $scope.criteria.purchasingRssdId != null &&
                $scope.criteria.validPurchasingRssdId &&
				$scope.criteria.historyTransactionDate != null) {
                returnValue = true;

            }
            if ($scope.newHeadSelected && $scope.criteria.newHeadNumber == null) {
                returnValue = false;
            }
            if (!validateTransactionDate()) {
                returnValue = false;
            }
            return returnValue;
        }


        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }


        $scope.openBranchDetail = function (branchId) {
            $stateParams.branchId = branchId;
                $uibModal.open({
                    animation: true,
                    modal: true,
                    size: 'lg',
                    templateUrl: '/AppJs/advanced/institutions/views/branch/_modaldetails.html',
                    controller: ['$scope', '$rootScope', '$state', '$stateParams', '$uibModal', 'AdvInstitutionsService', 'AdvBranchesService', 'toastr', '$log','$uibModalInstance',
                        function ($scope, $rootScope, $state, $stateParams, $uibModal, AdvInstitutionsService, AdvBranchesService, uiGridConstants, $log, $uibModalInstance) {

                            AdvBranchesService.getBranchDetail(branchId).then(function (result) {
                                $scope.instDataReady = false;
                                $scope.instData = result;
                                $scope.instDataReady = true;

                            });
                            $scope.cancel = function () {
                                $uibModalInstance.dismiss('cancel');
                            };
                        }]
                        //'AdvInstitutionBranchController'
                }).result.then(function (result) {

                }, function () {
                    //dismissed
                });
            };

        function activate() {
            //$timeout(function () {
            //    $('[id="historyTransactionDate"]')[0].focus();

            //}, 750);

			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}

            window.scrollTo(0, 0);
            $scope.instDataReady = true;
            $scope.Instchanged = false;

            if ($state.params.mode)
            {
                //set the soldrssdid 
                //if ($scope.criteria.soldRssdId)
				if ($state.params.soldRssdId)
                {
                    $scope.criteria.soldRssdId = $state.params.soldRssdId;
                }
                else
                {
                    $scope.criteria.soldRssdId = $state.params.rssd;
                }
                

                if ($state.params.mode == 'bankBranchSoldExisting')
                {
                    $scope.buyer = 'Bank';
                }
                else
                {   
                    $scope.buyer = 'Thrift';
                }
            }
           // $scope.buyer = capitalize($scope.buyer);
            $scope.buyer = capitalize($scope.buyer);
            
            AdvInstitutionsService.getInstitutionData({ rssdId:  $scope.criteria.soldRssdId, getDetail: getDetail, getBranches: getBranches, getOperatingMarkets: getOperatingMarkets, getHistory: getHistory }).then(function (result) {
                if (result.definition != null) {
                    $scope.sellingData = result.definition;
                    if ($scope.sellingData.class == 'BANK')
                    {
                        $scope.target = 'Bank';
                    }
                    else
                    {
                        $scope.target = 'Thrift';
                    }
                }
            });

        }

    }

    
    angular
         .module('app')
           .filter('instSoldFilter', function () {
               return function (dataArray, searchTerm) {
                   if (!dataArray) return;
                   if (searchTerm.$ == undefined) {
                       return dataArray
                   } else {
                       var term = searchTerm.$.toLowerCase();
                       return dataArray.filter(function (item) {
                           return checkVal(item.name, term)
                               || checkVal(item.county, term)
                               || checkVal(item.city, term)
                               || checkVal(item.zip, term)
                               || checkVal(item.state)
                       });
                   }
               }

               function checkVal(val, term) {
                   if (val == null || val == undefined)
                       return false;

                   return val.toLowerCase().indexOf(term) > -1;
               }
           });
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsStateDepositsListController', AdvInstitutionsStateDepositsListController);

    AdvInstitutionsStateDepositsListController.$inject = ['$scope', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', 'toastr'];




    function AdvInstitutionsStateDepositsListController($scope, $stateParams, $timeout, $templateCache, AdvInstitutionsService, toastr) {
        $scope.instData = [];
        $scope.instDataReady = false;
        $scope.instLoadData = false;
        $scope.totalDeposits = 0;
        $scope.hhi = 0;
        $scope.calProfForma = false;
        $scope.searchInstString = '';
        $scope.showCalProForma = false;
        $scope.isCheckedItems = false;

        angular.extend($scope, {
            THCData: [],
            HistorybyMarketDataLoaded: false,
            TopHoldClosedDataLoaded: true,
            gatherStatesByDeposits: handleStatesByDeposits,
        });

        activate();


        $scope.showSearchResults = function () {
            
            $scope.showdetails = true;
            $scope.instDataReady = false;
            $scope.instLoadData = false;
            $scope.criteria.calProfForma = null;
        };


        //Top Category options ===================================================
        $scope.instTypeItems = ["Banks", "Thrifts", "Topholds"];
        $scope.instTypeselected = [];

        $scope.toggleinstType = function (item, list) {
            var idx = list.indexOf(item);
            if (idx > -1) {
                list.splice(idx, 1);
            }
            else {
                list.push(item);
            }
        };

        $scope.instTypeexists = function (item, list) {
            return list.indexOf(item) > -1;
        };

        $scope.isIndeterminate = function () {
            return ($scope.selected.length !== 0 &&
                $scope.instTypeselected.length !== $scope.instTypeItems.length);
        };

        $scope.isChecked = function () {
            return $scope.instTypeselected.length === $scope.instTypeItems.length;
        };

        $scope.toggleAll = function () {
            if ($scope.instTypeselected.length === $scope.instTypeItems.length) {
                $scope.instTypeselected = [];
                $scope.isCheckedItems = false;
            } else if ($scope.instTypeselected.length === 0 || $scope.instTypeselected.length > 0) {
                $scope.instTypeselected = $scope.instTypeItems.slice(0);
                $scope.isCheckedItems = true;
            }
        };
        //Top Category options ===================================================


        $scope.showProFormaData = function ()
        {
            $scope.showCalProForma = !$scope.showCalProForma;
        }


        function activate() {
        }

        function handleStatesByDeposits() {

            if ($scope.criteria.state == null) {
                toastr.error('*** State is required');
                return;
            }

            if ($scope.instTypeselected == null) {
                toastr.error('*** Please choose at least one Institution Type.');
                return;
            }

            var data = {
                stateId: $scope.criteria.state.stateId,
                instType: $scope.instTypeselected,
                reportOptions: $scope.calProfForma,
                buyerRSSDID: $scope.criteria.buyerssdId,
                sellerRSSDID: $scope.criteria.sellerrssdId,
            };

            $scope.instLoadData = true;
            AdvInstitutionsService.getStateDeposits(data).then(function (result) {
                $scope.instData = result.data.resultdata;
                $scope.showdetails = false;
                $scope.instDataReady = true;
                $scope.instLoadData = false;
                $scope.totalDeposits = result.data.totalStateDeposits; //.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                $scope.hhi = result.data.hhi;
                $scope.depositCount = result.data.numberofRecords;
                $scope.searchInstString = parsetheSelectedArray();
                $scope.showCalProForma = false;
            });
        }

        function parsetheSelectedArray() {
            var parsestring = '';

            for (var i = 0; i < $scope.instTypeselected.length; i++) {
                parsestring = parsestring + ' ' + $scope.instTypeselected[i];
            }
            return parsestring;


        }
    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsTHCAdminController', AdvInstitutionsTHCAdminController);

    AdvInstitutionsTHCAdminController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', '$timeout', '$templateCache', '$log', 'AdvInstitutionsService', 'toastr', 'Dialogger', 'AdvPendingService'];

    function AdvInstitutionsTHCAdminController($scope, $rootScope, $state, StatesService, $timeout, $templateCache, $log, AdvInstitutionsService, toastr, Dialogger, AdvPendingService) {
        $scope.THCchanged = false;
        $scope.instData = [];
        $scope.selectRecord = false;
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
        $scope.contProcessing = true;
        $scope.THCeasesShowDetails = false;
        $scope.THCCeaseLoadData = false;
        $scope.THCCeasesFinishProcessing = false;
        $scope.THCAcquireProcessed = false;
        $scope.TCHCeasedAllowed = false;
        $scope.TCHAcquireAllowed = false;
        $scope.criteria = [];
        $scope.THCSurvivorData = []; //used for print confirm this is the survivor bank info
        $scope.THCSurvivorDataParentBankData = [];  //used for print confirm this is the top bank of a tophold
        $scope.txnIds = [];
        $scope.THCnonSurvivorData = []; //used for print confirm this is the non survivor bank info
        $scope.mode = '';
        $scope.runDate = new Date();
		$scope.pendingReady = true;
		$scope.criteria.packetId = null;
		$scope.criteria.transDateType = 'Consummation';

        //standard printing for confirmation and cancelling of a model
        $scope.printDiv = function (divName) {
            window.scrollTo(0, 0);

            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        // this is hacky, replace with better solution
        $scope.showCancel = function () {

            //return !$rootScope.isInWizard && $scope.$dismiss != null;
            return $scope.$dismiss;

        };


        $scope.cancel = function () {

            $scope.$dismiss();
            //$state.('root.adv.institutions.summary', { rssd: $scope.criteria.rssdId, isTophold: true });
            $state.reload();
        };

        $scope.getRSSDID = function () {
            var data =
            {
                SurvivorRssdId: $scope.criteria.survivorRSSDId,
                NonSurvivorRssdId: $scope.criteria.nonSurvivorRSSDIds
            }
            $scope.pendingReady = false;
            AdvPendingService.getPendingTHAcqTH(data).then(function (result) {
                if (result) {
                    if (result.length != 0) {
                        $scope.tophold = result;
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = true;
                    }
                    else {
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = false;
                    }
                }
                else {
                    $scope.pendingReady = true;
                    $scope.showPendingTransactions = false;
                }
                $scope.pending = true;
            });
        };

        activate();

    


        function populateTHCInformation(rssd)
        {
            $scope.LoadRSSDdata = true;

            AdvInstitutionsService
                .getInstitutionData({ rssdId: rssd, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                .then(function (data) {
                    $log.info(data);
                    $scope.criteria.rssdId = rssd;
                    $scope.THCData = data.definition;
                    $scope.THCeasesShowDetails = true;
                    $scope.THCCeaseLoadData = false;

                    if (data.definition.numberOfBanks > 0 || data.definition.numberOfThrifts > 0) {
                        toastr.error("This tophold has open subsidiaries. You must remove all subs before continuing.");
                        $scope.TCHCeasedAllowed = false;
                    }
                    else {
                        $scope.TCHCeasedAllowed = true;
                    }


            
                });
        }


        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.institutions";
        }


        $scope.loadTHC = function () {
            $scope.LoadRSSDdata = true;
            $log.info($scope.criteria.rssdId);

            populateTHCInformation($scope.criteria.rssdId);
        };

        function populateTHCSurvivor(rssd)
        {
            $log.info(rssd);

            AdvInstitutionsService
                .getInstitutionData({ rssdId: rssd, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                .then(function (data) {
                    $log.info(data);

                        $scope.THCSurvivorData = data.definition;
                        if (!$scope.THCSurvivorData)
                            toastr.error("Invalid Survivor RSSDID!");

                    
                   
                });
        }

        function populateTHCnonSurvivor(rssd) {
            $scope.LoadRSSDdata = true;
            $log.info($scope.criteria.rssdId);

            AdvInstitutionsService
                .getInstitutionData({ rssdId: rssd, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                .then(function (data) {
                    $log.info(data);
                    if ((data.definition.class == 'BHC') || (data.definition.class == 'THC') || (data.definition.class == 'SLHC') || (data.definition.class == 'DEO'))
                    {
                        $scope.THCnonSurvivorData = data.definition;
                        $scope.THCAcquireshowdetails = true;
                        //$scope.THCCeaseLoadData = false;

                    }
                    else
                    {
                       toastr.error("Invalid NonSurvivor RSSDID!  The NonSurvivor RSSDID must be a Tophold!");
                    }
                    
                     
                     
                });
        }


        $scope.loadTHCdata = function () {
            $scope.LoadRSSDdata = true;
            $log.info($scope.criteria.rssdId);
            if ($scope.criteria.rssdId) {
                populateTHCInformation($scope.criteria.rssdId);
            }

        };

        $scope.toggle = function (id, rssdid, memo, selectedPend) {
            $scope.txnIds = [];
            $scope.txnIds.push(id);

            $scope.criteria.pendingtransactionRSSDID = rssdid;
            $scope.criteria.pendingtransactionmemo = memo;
            $scope.criteria.selectedPend = selectedPend;


        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };

        $scope.loadTHCforMergers = function () {
            $scope.LoadRSSDdata = true;
            $log.info($scope.criteria.nonSurvivorRSSDIds);
            if ($scope.criteria.nonSurvivorRSSDIds) {
                //$scope.THCnonSurvivorData = populateTHC($scope.criteria.nonSurvivorRSSDIds);
                populateTHCnonSurvivor($scope.criteria.nonSurvivorRSSDIds);
                $scope.getRSSDID();
            }

        };



        $scope.saveChangesTHCMerge = function () {
            var d = new Date();
            $scope.contProcessing = true;

			if ($rootScope.FeatureToggles.ChangePacketIntegration && (($scope.criteria.packetId || -1) < 0)) {
				toastr.error("You must select a Firma change record packet!");
				$scope.contProcessing = false;
			}

			if (!$scope.criteria.nonSurvivorRSSDIds) {
                toastr.error("Non Survivor RSSDId is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.survivorRSSDId) {
                toastr.error("Survivor RSSDId is required!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.nonSurvivorRSSDIds == $scope.criteria.survivorRSSDId) {
                toastr.error("Non Survivor RSSDId cannot be the same as Survivor RSSDId!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.transactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.transDateType) {
                toastr.error("Transaction Date Type must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.transactionDate) {
                if (d <= $scope.criteria.transactionDate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.THCnonSurvivorData)
            {
                toastr.error("Invalid Non-Survivor RSSDID!");
                $scope.contProcessing = false;
            }



                       if ($scope.contProcessing == true) {

                           //get the Survivor and see if it is  THC and the non survivors has banks
                           //cannot move banks into a thrift
                           AdvInstitutionsService
                               .getInstitutionData({ rssdId: $scope.criteria.survivorRSSDId, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                               .then(function (data) {
                                   $log.info(data);
                                   $scope.THCSurvivorData = data.definition;
                                   if ($scope.THCSurvivorData.length == 0) {
                                       toastr.error("Invalid Survivor RSSDID!");
                                       return;
                                   }



                                  

                                   if (($scope.THCSurvivorData.class == 'THC' || $scope.THCSurvivorData.class == 'SLHC') && $scope.THCnonSurvivorData.class == 'BHC') {
                                       //verify we dont have banks under it

                                       
                                           Dialogger.confirm('An SLHC is acquiring a BHC, are you sure you want to continue?', null, true).then(function (result) {
                                               $scope.contProcessing = result;
                                               if ($scope.contProcessing == true) {
                                                   handleMergeTopHoldByRSSDID();
                                                   return;
                                               }

                                           });


                                     

                                   }
                                   else
                                   {
                                       //So check to see if we have a bank or thrift under it
                                       if (data.definition.orgs) {
                                           $scope.THCSurvivorDataParentBankData = data.definition.orgs;

                                       }
                                       //so we need to get the parent bank of this tophold
                                       //what is the parent Bank ID


                                       if ($scope.contProcessing == true) handleMergeTopHoldByRSSDID();
                                   }


                                   


                               });

                       }

                   


                

        };


        $scope.saveChangesTHCeases = function () {
            //validation
            var d = new Date();
            $scope.contProcessing = true;

			if ($rootScope.FeatureToggles.ChangePacketIntegration && (($scope.criteria.packetId || -1) < 0)) {
				toastr.error("You must select a Firma change record packet!");
				$scope.contProcessing = false;
			}

            if (!$scope.criteria.rssdId) {
                toastr.error("RSSDID is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.transDateType) {
                toastr.error("Transaction Date Type must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                if (d <= $scope.criteria.historyTransactionDate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }
            if ($scope.contProcessing == true)
            {
                Dialogger.confirm('Are you sure you want to delete this record?', null, true).then(function (result) {
                    $scope.contProcessing = result;
                    if ($scope.contProcessing == true)
                    handleCloseTopHoldByRSSDID();
                });


            }
                

        }



        function handleMergeTopHoldByRSSDID() {
            var data = {
                survivorRSSDId: $scope.criteria.survivorRSSDId,
                nonSurvivorRSSDIds: $scope.criteria.nonSurvivorRSSDIds,
                transactionDate: $scope.criteria.transactionDate,
                transDateType: $scope.criteria.transDateType,
				confirmationPromptReply: $scope.criteria.confirmationPromptReply,
				firmaPacketId: $scope.criteria.packetId
            };



            AdvInstitutionsService.postMergeTopHoldbyRSSDID(data).then(function (result) {
                if (result.errorFlag == false) {
                    toastr.success("Tophold - " + $scope.criteria.nonSurvivorRSSDIds + " was successfully acquired.");
                    //now remove the pending transaction - we need to remove the one they selected
                    if ($scope.txnIds)
                    {
                        AdvPendingService.getDeletedTransactions($scope.txnIds).then(function (result) {
                            //clear out items
                            toastr.success(result.errorMessage);

                        });

                    }
                    
                    $scope.instTHCData = [];
                    $scope.showdetails = false;
                    $scope.LoadRSSDdata = false;
                    $scope.THCAcquireProcessed = true;
                    $scope.showPendingTransactions = false;
                    
                }
                else
                    for (var i = 0; i < result.messageTextItems.length; i++) {
                        toastr.error(result.messageTextItems[i]);
                    }


            });

        };


        function handleCloseTopHoldByRSSDID() {
            var data = {
                rSSDId: $scope.criteria.rssdId,
                trandate: $scope.criteria.historyTransactionDate,
				transactionDateType: $scope.criteria.transDateType,
				firmaPacketId: $scope.criteria.packetId
            };

            AdvInstitutionsService.postCloseTopHoldbyRSSDID(data).then(function (result) {
                if (result.errorFlag == false) {
                    toastr.success("Tophold - " + $scope.THCData.name + " was successfully ceased.");
                    //clear out items
                    $scope.instTHCData = [];
                    $scope.THCeasesShowDetails = false;
                    $scope.THCCeaseLoadData = false;
                    $scope.THCCeasesFinishProcessing = true;
                    //show confirmation
                    
                }
                else
                    toastr.error("There was an unexpected error.", result.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
            });

        };


        function activate() {
			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}

			//move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                $('[id="historyTransactionDate _input"]')[0].focus();

            }, 750);

            window.scrollTo(0, 0);


            //$scope.criteria.transDateType = 'Consummation';


            AdvInstitutionsService.getSDFCodes().then(function (data) {
                $scope.sdfCodes = data;
            });

            StatesService.statesPromise.then(function (result) {
                var criteria = [];
                $scope.states = result;
                $scope.statesLoaded = true;

            });

            $scope.THCData = true;
            $scope.THCAdded = false;
            var rssd;



            // This is very hacky.  We need to find a better way of communicating the caller's intention
            if ($scope.$parent.criteria == null) {

                if ($scope.criteria) {
					//$scope.criteria.transDateType = 'Consummation';
                    rssd = $scope.criteria.rssdId ? $scope.criteria.rssdId : $state.params.rssd;
                    if ($state.params.mode == 'acquiring') {

                        $scope.criteria.survivorRSSDId = parseInt(rssd);
                        $scope.TCHAcquireAllowed = true;
                        $timeout(function () {
                            $('[id="survivorRSSDId"]')[0].focus();

                        }, 750);

                    }
                    else if ($state.params.mode == 'acquired') {
                        $scope.criteria.nonSurvivorRSSDIds = parseInt(rssd);
                        $scope.TCHAcquireAllowed = true;
                        $timeout(function () {
                            $('[id="survivorRSSDId"]')[0].focus();

                        }, 750);
                    }
                    else {
						//$scope.criteria.transDateType = 'Consummation';
                        $scope.criteria.rssdId = rssd;
                        populateTHCInformation(rssd);



                        $timeout(function () {
                            $('[id="rssdId"]')[0].focus();

                        }, 750);
                    }
                }
                else {
                    $scope.criteria.transDateType = 'Consummation';
                    rssd = $state.params.RSSDId ? $state.params.RSSDId : $state.params.rssd;
                    populateTHCInformation(rssd);
                    $timeout(function () {
                        $('[id="rssdId"]')[0].focus();

                    }, 750);
                }
            }
            else {
                rssd = $scope.$parent.criteria.rssdId ? $scope.$parent.criteria.rssdId : $state.params.rssd;
                if ($state.params.mode == 'acquiring') {
                    $scope.criteria.survivorRSSDId = parseInt(rssd);
                    //$scope.criteria.transDateType = 'Approval';
                    $scope.TCHAcquireAllowed = true;
                    $timeout(function () {
                        $('[id="survivorRSSDId"]')[0].focus();

                    }, 750);

                }
                else if ($state.params.mode == 'acquired') {
                    $scope.criteria.nonSurvivorRSSDIds = parseInt(rssd);
                    $scope.TCHAcquireAllowed = true;
                    $timeout(function () {
                        $('[id="survivorRSSDId"]')[0].focus();

                    }, 750);
                }
                else {
                    populateTHCInformation(rssd);
                }


            }
            //}

            //take the value passed in and then populate the screen


        };

    }
})();;
/// <reference path="AdvInstitutionsListController.js" />

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsUnAssoicateController', AdvInstitutionsUnAssoicateController);

    AdvInstitutionsUnAssoicateController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', 'Dialogger', 'toastr', 'uibDateParser', 'AdvPendingService', '$timeout', 'AdvBranchesService', 'genericService'];


    function AdvInstitutionsUnAssoicateController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, Dialogger, toastr, uibDateParser, AdvPendingService, $timeout, AdvBranchesService, genericService) {
        $scope.txnIds = [];
        $scope.runDate = new Date();
		$scope.pendingReady = true;
		$scope.criteria = [];
		$scope.criteria.packetId = null;
		$scope.criteria.transactionDateType = 2;

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

            var d = new Date();
            $scope.entrydate = d;

			//verify we have a firma packet selected
			if ($rootScope.FeatureToggles.ChangePacketIntegration && (!$scope.criteria.packetId || isNaN($scope.criteria.packetId))) {
				toastr.error("Record packet selection is required!");
				$scope.contProcessing = false;
			}

            //verify we have required data
            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.transactionDateType) {
                toastr.error("Transaction Type must be entered!");
                $scope.contProcessing = false;
            }            

            if ($scope.contProcessing) { processchange(); }           
        };


       

        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = [];
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

       

        function processchange() {
            if ($scope.contProcessing == true) {
                //send the new Tophold to the services later
                // function postInstitution(id, inst) {
                var data =
                    {
                        bypassHistory: $scope.criteria.bypassHistory,
                        institutionId: $scope.criteria.id,
                        transDate: $scope.criteria.historyTransactionDate,
						transDateType: $scope.criteria.transactionDateType,
						firmaPacketId: $scope.criteria.packetId 
                    }
                process(data);
            }
        }

        function process(data) {
            AdvInstitutionsService.postConvertControlledInstitutionToIndependent(data)
                        .then(function (data) {
                            //did we have success if yes then we need to do something
                            if (data.errorFlag == false) {

                                
                                toastr.success("Successfully Disassociated Institution");
                            
                            $scope.InstShowdetails = false;
                            $scope.InstDone = true;


                            }
                            else {
                                if (data.messageTextItems.length > 0) {
                                    for (var i = 0; i < data.messageTextItems.length; i++) {
                                        toastr.error(data.messageTextItems[i]);
                                    }
                                }
                            }
                        });


        }

        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        // this is hacky, replace with better solution
        $scope.showCancel = function () {

            return !$rootScope.isInWizard && $scope.$dismiss != null;

        };


        $scope.cancel = function () {

            $scope.$dismiss();
            //$state.go('root.adv.institutions.instsearch', $scope.reloadData, { reload: true });
            //$state.('root.adv.institutions.summary', { rssd: $scope.criteria.rssdId, isTophold: true });
			$state.go;
			$state.reload();
        };


        activate();
        function activate() {   
			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}

			//move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                $('[id="historyTransactionDate _input"]')[0].focus();

            }, 750);

            window.scrollTo(0, 0);
            var rssd

            if ($state.params.MergedRSSDID)
            {
                rssd = $state.params.MergedRSSDID;
            }
            else
            {
                rssd = $state.params.rssd;
            }           

            $scope.ReadyToAcquire = true;
            $scope.Doneacquiring = false;
            genericService.getStates().then(function (result) {
                var criteria = [];
                $scope.criteria = [];
                $scope.states = result;                

                //find the criteria that was passed in of the screen that call the form
                //$state.params.reloadData
                $scope.reloadData = $state.params.reloadData;

                AdvInstitutionsService.getEditInstitutionData({ rssdId: rssd }).then(function (result) {
                    if (result && result != null) {
                        //countyFIPSNum
                        var criteria = result;

                        // init values for history buttons
                        criteria.transactionDateType = 2; // consummation date
                        criteria.bypassHistory = false;

                        criteria.type = result.type;


                        criteria.state = _.find($scope.states, { stateId: result.stateId });

                        genericService.getCounties(result.stateId).then(function (resultCounty) {
                            criteria.state.counties = resultCounty;

                            criteria.county = _.find(criteria.state.counties, { countyId: result.countyId });

                            var dataCity = {
                                stateId: result.stateId,
                                countyId: result.countyId
                            }
                            genericService.getCities(dataCity).then(function (resultCity) {
                                criteria.county.city = resultCity;
                                criteria.city = _.find(criteria.county.city, { cityId: result.cityId });

                                criteria.InstCategoryId = criteria.entityTypeCode == 'BANK' ? 'B' : 'T';
                                criteria.InstType = criteria.entityTypeCode == 'BANK' ? 'Bank' : 'Thrift';

                                //if we have a parent RSSDID for the Parent Inst then it is controlled

                                $scope.pageTitle = "Disassociate " + criteria.InstType + " from Tophold";


                                $scope.criteria = criteria;

                                $scope.InstShowdetails = true;
                                $scope.InstDone = false;
                            });
                        });
                    }

                    $scope.institutionLoaded = true;
                });
            });
        }
    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvTopholdEditController', AdvTopholdEditController);

    AdvTopholdEditController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', 'Dialogger', 'toastr', 'uibDateParser', 'AdvPendingService', '$timeout','genericService'];

    function AdvTopholdEditController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, Dialogger, toastr, uibDateParser, AdvPendingService, $timeout, genericService) {
        $scope.txnIds = [];
        $scope.tophold = [];
        $scope.newcitymode = false;
        $scope.THCchanged = false;
        $scope.instData = [];
        $scope.selectRecord = false;
        $scope.pretophold;
        $scope.institutionLoaded = false;
        $scope.entrydate = new Date();
        $scope.showPendingTransactions = false;
        $scope.contProcessing = true;
        $scope.THCeasesShowDetails = false;
        $scope.THCCeaseLoadData = false;
        $scope.THCCeasesFinishProcessing = false;
        $scope.pendingReady = true;
		$scope.showCont = false;
		$scope.criteria = [];
		$scope.criteria.packetId = null;
		$scope.criteria.transactionDateType = 2;
        $scope.showPendingTransactionsRemovedmsg = false;
        //$scope.saveChanges = function () {
        //    $scope.THCAdded = true;

        //};


        $scope.switchNewCity = function () {
            $scope.newcitymode = !$scope.newcitymode;
        };


        $scope.openAcquiredForm = function (actioname) {
            $state.params.mode = actioname;
            $state.params.rssd = $scope.criteria.rssdId;
            $state.params.TopHoldrssdId = $scope.criteria.rssdId;
			$state.params.historyTransactionDate = $scope.criteria.historyTransactionDate;
			$state.params.packetId = $scope.criteria.packetId;

            if (actioname == 'acquiring')
            {
				AdvInstitutionsService.TopholdAcquired($scope.criteria.rssdId, actioname, $scope.criteria.packetId);
            }
            else if(actioname == 'acquiringinst')
            {
                AdvInstitutionsService.TopholdAcquiredInst($scope.criteria.rssdId, actioname,$scope.criteria.historyTransactionDate, $scope.criteria.packetId);
            }
            else
            {

            }
            

        }

         

        

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

			var d = new Date();

			// verify that a packet is selected if it is neessary for processing
			if (($scope.criteria.bypassHistory || false) == false && $rootScope.FeatureToggles.ChangePacketIntegration && ($scope.criteria.packetId || -1) < 0) {
				toastr.error("To create a history record, you must select a record packet.");
				$scope.contProcessing = false;
			}

            //verify we have transaction date, name, primary 
            if (!$scope.criteria.rssdId) {
                toastr.error("RSSDID is required!");
                $scope.contProcessing = false;
			}

            if (!$scope.criteria.historyTransactionDate) {
                toastr.error("Transaction Date must be entered!");
                $scope.contProcessing = false;
            }

            if ($scope.criteria.historyTransactionDate) {
                var transdate = new Date($scope.criteria.historyTransactionDate);
                if (d <= transdate) {
                    toastr.error("Transaction Date must be Current or Previous date!");
                    $scope.contProcessing = false;
                }
            }

            if (!$scope.criteria.transactionDateType) {
                toastr.error("Transaction Type must be entered!");
                $scope.contProcessing = false;
			}

			if ($scope.recMode == "Tophold Formation " && $rootScope.FeatureToggles.ChangePacketIntegration && $scope.criteria.packetId == null) {
				toastr.error("Tophold creation requires selection of the change packet");
				$scope.contProcessing = false;
			}

            if (!$scope.criteria.name) {
                toastr.error("Name is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.city) {
                toastr.error("City is required!");
                $scope.contProcessing = false;

            }
            if (!$scope.criteria.state && $scope.criteria.international != true) {
                toastr.error("State is required!");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.county && $scope.criteria.international != true) {
                toastr.error("County is required!");
                $scope.contProcessing = false;

            }

            if (!$scope.criteria.district) {
                if ($scope.criteria.international != true)
                {
                    toastr.error("FRS DISTRICT must be between 0 and 12!");
                    $scope.contProcessing = false;
                }
                else
                {
                    if ($scope.criteria.district != 0)
                    {
                        toastr.error("FRS DISTRICT must be 0 for international Cities");
                        $scope.contProcessing = false;
                    }
                }

               

            }



            //check to see if we changed the entity Type Code
            if ($scope.THCChanged && $scope.contProcessing) {
                if ($scope.pretophold.entityTypeCode == 'DEO')
                {
                    processchange();
                }
                else if(($scope.pretophold.entityTypeCode == 'SLHC' || $scope.pretophold.entityTypeCode == 'THC')  && $scope.criteria.entityTypeCode == 'BHC')
                {
					if ($scope.criteria.numberOfThrifts > 0) {
						Dialogger.confirm('The Tophold has thrift subsidiaries which will have their HHI weight modified. <br />Do you want to continue?', null, true).then(function (result) {
							$scope.contProcessing = result;
							processchange();
						});
					}
					else {
						processchange();
					}
                }
                else if (($scope.pretophold.entityTypeCode == 'BHC' ) && $scope.criteria.entityTypeCode == 'SLHC') {
					var dialogMsg = '';
					if ($scope.criteria.numberOfBanks > 0) {
						dialogMsg += 'The Tophold has a bank subsidiary, which is not allowed under an SLHC. <br />';
					}
					if ($scope.criteria.numberOfThrifts > 0) {
						dialogMsg += 'The Tophold has thrift subsidiaries which will have their HHI weight modified. <br />';
					}
					if (dialogMsg.length > 0) {
                        Dialogger.confirm(dialogMsg + 'Do you want to continue?', null, true).then(function (result) {
                            $scope.contProcessing = result;
                            processchange();
                        });
					}
					else {
                        processchange();
                    }
                }
				else if ($scope.criteria.entityTypeCode == 'DEO') {
                    if ($scope.criteria.numberOfBanks > 0 || $scope.criteria.numberOfThrifts > 0) {
                        Dialogger.confirm('The Tophold has institution(s) subsidiary. <br />Do you want to continue?', null, true).then(function (result) {
                            $scope.contProcessing = result;
                            processchange();
                        });

                    }
                    else {
                        processchange();
                    }
                }
                else {
                    processchange();
                }
            
            }
            else {
                processchange();
            }

        };

        function processchange() {
            if ($scope.recMode == "Tophold Formation ") {
                if ($scope.contProcessing == true) {
                    //send the new Tophold to the services later
                    // function postInstitution(id, inst) {
                    var instUpdDTO =
                        {
                            RSSDId: $scope.criteria.rssdId,
                            historyTransactionDate: $scope.criteria.historyTransactionDate,
                            EntityTypeCode: $scope.criteria.entityTypeCode,
                            Name: $scope.criteria.name,
                            StateId: $scope.criteria.international != true  ? $scope.criteria.state.stateId : 0,
                            CountyId: $scope.criteria.international != true ? $scope.criteria.county.countyId : 0,
                            CityId: $scope.criteria.city.cityId,
                            country: $scope.criteria.international != true ? $scope.criteria.country : $scope.criteria.intcountry,
                            DistrictId: $scope.criteria.district,
                            ActPrimCd: $scope.criteria.actPrimCd,
                            id: $scope.criteria.id,
							IsFHC: $scope.criteria.isFHC							
                        }


                    var data = {
                        tophold: instUpdDTO,
                        bypassHistory: false,
                        transDate: $scope.criteria.historyTransactionDate,
                        transType: $scope.criteria.transactionDateType,
						transactionId: $scope.txnIds,
						changePacketId: $scope.criteria.packetId
                    }

                    processTopHold(id, data);



                }
            }
            else {
                //this is an edit
                if ($scope.contProcessing == true) {
                    //send the new Tophold to the services later
                    // function postInstitution(id, inst) {
                    var instUpdDTO =
                        {
                            RSSDId: $scope.criteria.rssdId,
                            historyTransactionDate: $scope.criteria.historyTransactionDate,
                            EntityTypeCode: $scope.criteria.entityTypeCode,
                            Name: $scope.criteria.name,
                            StateId: $scope.criteria.international != true  ? $scope.criteria.state.stateId : 0,
                            CountyId: $scope.criteria.international != true ? $scope.criteria.county.countyId : 0,
                            CityId: $scope.criteria.city.cityId,
                            country: $scope.criteria.country,
                            DistrictId: $scope.criteria.district,
                            ActPrimCd: $scope.criteria.actPrimCd,
                            id: $scope.criteria.id,
                            IsFHC: $scope.criteria.isFHC
                        }

                    var id = $scope.criteria.id;

                    var data = {
                        tophold: instUpdDTO,
                        bypassHistory: $scope.criteria.bypassHistory,
                        transDate: $scope.criteria.historyTransactionDate,
                        transType: $scope.criteria.transactionDateType,
						transactionId: $scope.txnIds,
						firmaPacketId: $scope.criteria.packetId
                    }

                    processTopHold(id, data);




                }
            }
        }

        function processTopHold(id, data) {

            AdvInstitutionsService.postTophold(id, data).then(function (results) {
                if (results.errorFlag == false) {
                    $scope.THCAdded = true;
                    $scope.THCData = false;
                    $scope.pendingReady = false;
                    if (id) {
                        $scope.THCchanged = true;
                        $scope.THCAdded = false;
                        $scope.THCData = false;
						toastr.success("Tophold was updated");
						if (results.affectedItemCount > 1) {
							toastr.success(results.affectedItemCount - 1 + " thrift(s): Updated HHI weight");
						}
                        window.scrollTo(0, 0);
                        $scope.pendingReady = true;

                    }
                    else {
                        $scope.THCchanged = false;
                        $scope.THCAdded = true;
                        $scope.THCData = false;
                        toastr.success("Tophold was created");
                        window.scrollTo(0, 0);
                        if ($scope.criteria.selectedPend) {
                            $scope.showPendingTransactions = false;
                            $scope.showPendingTransactionsRemovedmsg = true;
                        }
                        $scope.pendingReady = true;

                    }

                }
                else {
                    //var errorMessage = [];
                    if (results.messageTextItems.length > 0) {
                        for (var i = 0; i < results.messageTextItems.length; i++) {
                            toastr.error(results.messageTextItems[i]);
                        }
                    }                   
                }


            }, function (err) {
                alert("Sorry. There was an error.");
            });

        }


        $scope.maxLengthCheck = function (object) {
            if (object.value.length > object.maxLength)
                object.value = object.value.slice(0, object.maxLength)
        };



        $scope.updateDistrict = function () {
           if ($scope.criteria.international == true)
                {
                    $scope.criteria.district = 0
                }
            };

        $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /[0-9]|\./;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
            }
        };

       



        $scope.openSw = function ()
        {
            $scope.showCont = $scope.showCont ? false : true;
        }

         

        $scope.UpdateCounties = function () {
            $scope.criteria.city = null;
            $scope.criteria.county = null;

            genericService.getCounties($scope.criteria.state.stateId).then(function (result) {
                $scope.criteria.state.counties = result;
            });




        }

        $scope.UpdateCities = function () {
            var data =
            {
                stateId: $scope.criteria.state.stateId,
                countyId: $scope.criteria.county.countyId
            }

            //populate the city from the county and state dropdown
            genericService.getCities(data).then(function (result) {
                $scope.criteria.county.city = result;
            });




        }



        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        // this is hacky, replace with better solution
        $scope.showCancel = function () {

            return !$rootScope.isInWizard && $scope.$dismiss != null;

        };


        $scope.cancel = function () {

            $scope.$dismiss();
            //$state.('root.adv.institutions.summary', { rssd: $scope.criteria.rssdId, isTophold: true });
            $state.reload();
        };


        $scope.toggle = function (id, rssdid, memo, selectedPend) {
            $scope.txnIds = [];
            $scope.txnIds.push(id);

            $scope.criteria.pendingtransactionRSSDID = rssdid;
            $scope.criteria.pendingtransactionmemo = memo;
            $scope.criteria.selectedPend = selectedPend;


        };

        $scope.isChecked = function (id) {
            return $scope.txnIds.indexOf(id) > -1;
        };

        $scope.clearButtons = function () {
            if ($scope.txnIds.length > 0) {
                $scope.txnIds = [];
            }
            else {
                toastr.success("No Pending Transactions have been selected!");
            }
        };

        $scope.getRSSDID = function () {
            var data =
            {
                SurvivorRssdId: $scope.criteria.rssdId
            }
            $scope.pendingReady = false;
            AdvPendingService.getPendingTopholds(data).then(function (result) {
                if (result) {
                    if (result.length != 0) {
                        $scope.tophold = result;
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = true;
                    }
                    else {
                        $scope.pendingReady = true;
                        $scope.showPendingTransactions = false;
                    }
                }
                else {
                    $scope.pendingReady = true;
                    $scope.showPendingTransactions = false;
                }
                $scope.pending = true;
            });

        };


        $scope.gatherNationalCity = function(nationId)
        {
            StatesService.getNationCities(nationId).then(function (result) {
                $scope.instCity = result;
            });

            $scope.criteria.district = 0;
            
        }

        $scope.populateDistrictID = function () {
            var data =
            {
                stateFipsId: $scope.criteria.state.stateId,
                countyId: $scope.criteria.county.countyId
            }


            AdvInstitutionsService.getDistrictByLocation(data).then(function (data) {
                if (data.errorFlag == false) {
                    //now update the  instUpdDTO object
                    $scope.criteria.district = data.districtId;
                }
                else {
                    //there was an error toast and exit
                    $scope.criteria.district = 0;
                }
            }, function (err) {
                alert("Sorry. There was an error.");
            });

            var dataCity =
          {
              stateId: $scope.criteria.state.stateId,
              countyId: $scope.criteria.county.countyId
          }

            //populate the city from the county and state dropdown
            genericService.getCities(dataCity).then(function (result) {
                $scope.criteria.county.city = result;
            });

        };

        $scope.getActivityCode = function () {

            var statusType = $scope.criteria.entityTypeCode;
            switch (statusType) {
                case "BHC":
                    $scope.criteria.actPrimCd = 551111;
                    break;
                case "SLHC":
                    $scope.criteria.actPrimCd = 551112;
                    break;
                case "DEO":
                    $scope.criteria.actPrimCd = 551114;
                    break;
                default:
                    $scope.criteria.actPrimCd = 0;
                    break;

            }

        };

        activate();

		function activate() {
			if ($rootScope.FeatureToggles.ChangePacketIntegration == false) {
				$scope.criteria.packetId = -1;
			}

            //move to the top of the screen and set focus on the RSSDID
            $timeout(function () {
                $('[id="historyTransactionDate _input"]')[0].focus();

            }, 750);

            window.scrollTo(0, 0);

            AdvInstitutionsService.getSDFCodes().then(function (data) {
                $scope.sdfCodes = data;
            });  
            genericService.getStates().then(function (result) {
                var criteria = [];
                $scope.criteria = [];
                $scope.states = result;
                $scope.statesLoaded = true;
                $scope.THCData = true;
                $scope.THCAdded = false;
                var rssd;
                var lookupmode;


                // This is very hacky.  We need to find a better way of communicating the caller's intention
                if ($scope.$parent.$parent == null || $scope.$parent.$parent.lookupMode != "AddTophold") {

                    if ($scope.criteria) {
                        rssd = $scope.criteria.rssdId ? $scope.criteria.rssdId : $state.params.rssd;
                        //$scope.getRSSDID();
                    }
                    else {
                        rssd = $state.params.RSSDId ? $state.params.RSSDId : $state.params.rssd;
                    }
                }
                else {
                    rssd = $scope.criteria.rssdId ? $scope.criteria.rssdId : $state.params.rssd;
                    lookupmode = $scope.$parent.$parent.lookupMode ;
                }
                


                //populate the nation drop down
                StatesService.getNations(true).then(function (result) {
                    $scope.nations = result;
                });

				if (rssd == null || rssd == '' || isNaN(rssd)) {
					$state.go('root.adv.institutions'); // we don't have any rssd info, go to index
				}
				else if (lookupmode == "AddTophold") {
                    $scope.recMode = "Tophold Formation ";
                    $scope.pageTitle = "Tophold Formation";
                    $scope.runDate = new Date();
                    $scope.criteria.actPrimCd = 551111;
                    $scope.criteria.country = 'U.S.A';
                    $scope.criteria.isFHC = false;
                    $scope.criteria.entityTypeCode = 'BHC';
                    $scope.runDate = new Date();
                    $scope.showPendingTransactions = true;
                    $scope.criteria.transactionDateType = 2;
                    $scope.criteria.international = false;
                    $scope.criteria.rssdId = rssd;
                    $scope.showCont = false;
                    $scope.getRSSDID();
                }
                else {
                    //moved the loading inside each if statement, yes it is dup need to clean this up
                    //but needed it done
                    
                    AdvInstitutionsService.getEditTopholdData({ rssdId: rssd }).then(function (result) {
                        if (result && result != null) {
                            //countyFIPSNum
                            $scope.pageTitle = "Tophold Attribute Update";
                            var criteria = result;
                            var preCriteria = result;
                            if (result.countyId != 0)
                            {
                                criteria.international = false;
                                criteria.state = _.find($scope.states, { stateId: result.stateId });
                                
                                genericService.getCounties(result.stateId).then(function (resultCounty) {
                                    criteria.state.counties = resultCounty;

                                    criteria.county = _.find(criteria.state.counties, { countyId: result.countyId });

                                    var dataCity = {
                                        stateId: result.stateId,
                                        countyId: result.countyId
                                    }
                                    genericService.getCities(dataCity).then(function (resultCity) {
                                        criteria.county.city = resultCity;
                                        criteria.city = _.find(criteria.county.city, { cityId: result.cityId });


                                   

                                    criteria.sdfCode = _.find($scope.sdfCodes, { name: result.sdf });
                                    criteria.transactionDateType = 2;
                                    criteria.bypassHistory = false
                                    $scope.instDataReady = true;
                                    $scope.criteria = criteria;
                                    preCriteria = angular.copy(criteria);
                                    $scope.pretophold = preCriteria;
                                    $scope.recMode = "Edit Tophold";
                                    $scope.THCData = true;
                                    $scope.THCAdded = false;
                                    $scope.THCChanged = true;
                                    $scope.showPendingTransactions = false;
                                    $scope.pendingReady = true;
                                    });
                                });



                                
                            }
                            else
                            {
                                criteria.international = true;
                                criteria.intcountry = _.find($scope.nations, { name: result.country });

                                StatesService.getNationCities(criteria.intcountry.nationId).then(function (nationresults) {
                                    $scope.instCity = nationresults;
                                    criteria.city = _.find($scope.instCity, { cityId: result.cityId });
                                    criteria.sdfCode = _.find($scope.sdfCodes, { name: result.sdf });
                                    criteria.transactionDateType = 2;
                                    criteria.bypassHistory = false
                                    $scope.instDataReady = true;
                                    $scope.criteria = criteria;
                                    preCriteria = angular.copy(criteria);
                                    $scope.pretophold = preCriteria;
                                    $scope.recMode = "Edit Tophold";
                                    $scope.THCData = true;
                                    $scope.THCAdded = false;
                                    $scope.THCChanged = true;
                                    $scope.showPendingTransactions = false;
                                });

                                
                               
                                
                            }
                            
                            
                        }
                        $scope.institutionLoaded = true;
                    });
                }




            });

        }





        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.institutions";
        }


        //Ceases methods
        //variable to use for the ceases
        //$scope.THCeasesShowDetails = false;  -- for showing the details once we have data loaded
        //$scope.THCCeaseLoadData = false; -- for refresh icon to show when we are loading the data
        //$scope.THCCeasesFinishProcessing = false;  -- when we are done and ready to show the finish processing


        $scope.loadTHC = function () {
            $scope.LoadRSSDdata = true;
            $log.info($scope.criteria.rssdId);

            AdvInstitutionsService
                .getInstitutionData({ rssdId: $scope.criteria.rssdId, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                .then(function (data) {
                    $log.info(data);
                    $scope.THCData = data.definition;
                    $scope.THCeasesShowDetails = true;
                    $scope.THCCeaseLoadData = false;

                    if (data.definition.numberOfBanks > 0 || data.definition.numberOfThrifts > 0) {
                        toastr.error("This tophold has open subsidiaries. You must remove all subs before continuing.");
                        $scope.THCcanClose = false;
                    }
                    else {
                        $scope.THCcanClose = true;
                    }




                });
        };

        $scope.saveChangesTHCeases = function () {
            //validation


            handleCloseTopHoldByRSSDID();

        }

        function handleCloseTopHoldByRSSDID() {
            var data = {
                rSSDId: $scope.criteria.rssdId,
                trandate: $scope.criteria.transactionDate,
                transactionDateType: 2
            };

            AdvInstitutionsService.postCloseTopHoldbyRSSDID(data).then(function (result) {
                if (result.errorFlag == false) {
                    toastr.success("Tophold - " + $scope.THCData.name + " was successfully closed.");
                    //clear out items
                    $scope.instTHCData = [];
                    $scope.THCeasesShowDetails = false;
                    $scope.THCCeaseLoadData = false;
                }
                else
                    toastr.error("There was an unexpected error.", result.messageTextItems[0] || "Please try again or contact support. Sorry about that.");
            });

        };


    }
})();;
(function () {
    angular.module('app')
           .directive('insitutionActionBox', insitutionActionBox);

    insitutionActionBox.$inject = ['$log', 'AdvInstitutionsService', '$timeout', 'UserData', '$state', '$window', 'AdvBranchesService','toastr'];

    function insitutionActionBox($log, AdvInstitutionsService, $timeout, UserData, $state, $window, AdvBranchesService, toastr) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            templateUrl: '/AppJs/advanced/institutions/directives/InsitutionActionBox_Template.html',
            scope: {
                inst: "=",
                direction: "=",
                reLoad: "=",
                menutype: "="
            }
        };
        return directive;

        function link(scope, element, attrs) {

            scope.openEditForm = function (rssdId, mode, parentRSSD) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.parentRSSD = parentRSSD;
                $state.params.rssdId = rssdId;
                $state.params.rssd = rssdId;

                if (mode == 'AddBank' || mode == 'AddThrift') {
                    AdvInstitutionsService.addOrEditInstitution(rssdId);
                }
                else {
                    if (scope.inst.class == 'THC' || scope.inst.class == 'SLHC' || scope.inst.class == 'BHC' || scope.inst.class == 'DEO') {
                        AdvInstitutionsService.addOrEditTophold(rssdId);
                    }
                    else {
                        AdvInstitutionsService.addOrEditInstitution(rssdId);
                    }
                }
            }


            scope.saveRssdID = function () {

                AdvInstitutionsService
                    .getNonHHIInstitutionsSearchData({ rssd: scope.inst.rssdId })
                    .then(function (result) {
                        if (angular.isArray(result) && result.length == 1) {
                            UserData.institutions.save(result[0]);
                        }
                    });

            };

            scope.openEditBranchFormOpening = function (ParentRSSDID, criteria, mode) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.BankRSSDID = ParentRSSDID;
                $state.params.Bankcriteria = criteria;

                AdvInstitutionsService.addOrEditBranch(null);


            };


            scope.openSoldToBankThrift = function (soldRSSDID, mode) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.soldRssdId = soldRSSDID;

                AdvInstitutionsService.opensoldBranchtoBankorThrift(null);


            };


            scope.openMergeIntoExistBankThrift = function (MergedRSSDID, mode) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.MergedRSSDID = MergedRSSDID;

                AdvInstitutionsService.openMergeInfoBankorThrift(null);


            };

            scope.openMergeIntoExistCU = function (MergedRSSDID, mode) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.MergedRSSDID = MergedRSSDID;

                AdvInstitutionsService.openMergeInfoCU(null);


            };


            scope.openUnAssociatedInst = function (MergedRSSDID) {
                //set the state params so we can use thru out app
                $state.params.mode = 'openUnAssociatedInst';
                $state.params.MergedRSSDID = MergedRSSDID;

                AdvInstitutionsService.openInstToUnAssociates(null);


            };


            scope.openFailureDepPayoffBankThrift = function (RSSDID, mode) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.MergedRSSDID = RSSDID;

                AdvInstitutionsService.openFailureDepPayoffBankorThrift(null);


            };

            scope.isSavedBranch = function (branch) {
                var returnValue = true;

                var value = UserData.institutions.isSavedBranch(branch);

                if (value) {
                    if (value == false)
                        returnValue = true;
                    else
                        returnValue = false;
                }
                return returnValue;

            }
            scope.isSavedInstitution = function (institution) {
                var returnValue = false;

                var value = UserData.institutions.isSaved(institution);

                if (value == false)
                    returnValue = true;
                else
                    returnValue = false;

                return returnValue;

            }
            scope.toggleBranchTarget = function (branch) {

                branch.parentRssdId = Number(branch.parentRssdId);
                branch.branchId = branch.branchId;

                AdvInstitutionsService.getNonHHIInstitutionsSearchData({ rssd: branch.parentRssdId }).then(function (result) {
                    if (result) {
                        if (!UserData.institutions.findSavedInstitution(result[0]));
                        UserData.institutions.save(result[0]);
                        UserData.institutions.saveBranch(branch);
                        scope.isSavedBranch(branch);
                        scope.isSavedInstitution(result[0]);
                        toastr.success("Success: Branch was saved to the session");
                        
                    }

                });

            }

            scope.goToNearestTab = function (branch) {

                $state.go('root.adv.institutions.branch.nearest', { branchId: branch.branchId });
            }
            //tophold methods
            scope.openAcquiredByTophold = function (RSSDID, mode, reLoadData) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.rssd = RSSDID;
                $state.params.reloadData = reLoadData;

                AdvInstitutionsService.postAcquiredByTophold(RSSDID);


            };

            scope.openAcquiredForm = function (acqInfo) {
                $state.params.mode = acqInfo.mode;
                $state.params.rssd = acqInfo.rssd;
                $state.params.TopHoldrssdId = acqInfo.rssd;
                $state.params.TransactionDate = acqInfo.historyTransactionDate;

                if (scope.inst.orgType == 'Tophold' || scope.inst.class == 'BHC' || scope.inst.class == 'SLHC' || scope.inst.class == 'DEO') {
                    AdvInstitutionsService.TopholdAcquired(acqInfo.rssd, acqInfo.mode);
                }
                else {
                    AdvInstitutionsService.InstAcquired(acqInfo.rssd, acqInfo.mode);
                }

            }

            scope.openCeasesForm = function (rssdId) {
                $state.params.rssd = rssdId.rssd;

                if (scope.inst.orgType == 'Tophold' || scope.inst.class == 'BHC' || scope.inst.class == 'SLHC' || scope.inst.class == 'DEO') {
                    AdvInstitutionsService.TopholdCeases(rssdId);
                }
                else {
                    AdvInstitutionsService.InstCeases(rssdId);
                }
            }

            scope.openPrintForm = function (data, reportType) {
                var jData = angular.toJson(data);
                //set the state params so we can use thru out app
                $state.params.reportType = reportType;
                $state.params.rptData = jData;

                $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
            };


            scope.getAlignmentClass = function () {
                return scope.direction != 'right' ? 'pull-left' : 'pull-right';
            }

            scope.isBranch = function () {
                return scope.menutype == 'branch' ? true : false
            };

            scope.openEditBranchForm = function (branchID, mode) {
                //set the state params so we can use thru out app
                $state.params.mode = mode;
                $state.params.branchId = branchID;

                AdvInstitutionsService.addOrEditBranch(branchID);


            };

            scope.openEditGeocodeForm = function (branchID) {
                $state.params.branchId = branchID;


                AdvBranchesService.openEditGeocodeForm(branchID);

            };

        }
    };
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionBranchController', AdvInstitutionBranchController);

    AdvInstitutionBranchController.$inject = ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$templateCache', '$uibModal', 'AdvInstitutionsService', 'AdvBranchesService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants', 'toastr', '$log', '$window'];

    function AdvInstitutionBranchController($scope, $rootScope, $state, $stateParams, $timeout, $templateCache, $uibModal, AdvInstitutionsService, AdvBranchesService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants, toastr, $log, $window) {

        
        $scope.toggleBranchTarget = function (branch) {

            branch.parentRssdId = Number(branch.parentRssdId);
            //branch.branchId = branch.id;

            AdvInstitutionsService.getNonHHIInstitutionsSearchData({ rssd: branch.parentRssdId }).then(function (result) {
                if (result) {
                    if (!UserData.institutions.findSavedInstitution(result[0]));
                    UserData.institutions.save(result[0]);
                    UserData.institutions.saveBranch(branch);
                }

            });
        }

        $scope.isSavedBranch = function (branch) {
            //branch.parentRssdId = Number(branch.parentRssdId);
            //return UserData.institutions.isSavedBranch(branch);
        }

     
        $scope.tabs = [
                     { heading: "Branch Details", route: "root.adv.institutions.branch.details", active: false },
                     { heading: "Branch Geocode", route: "root.adv.institutions.branch.geocode", active: false },
                     { heading: "Find Nearest Branches", route: "root.adv.institutions.branch.nearest", active: false },
                     { heading: "Map This and Nearest Branches", route: "root.adv.institutions.branch.map", active: false },
                     { heading: "Market Branch Distances", route: "root.adv.institutions.branch.marketdistances", active: false }
        ];


        $scope.go = function (route) {
            var data = {
                rssd: $state.params.rssd
            };
            $state.go(route, data);
        };
        $scope.active = function (route) {
            return $state.is(route);
        };
        //$scope.goBack = function () {
        //    window.history.back(-historyBack);
        //}
        $scope.$on("$stateChangeSuccess", function () {
            $scope.tabs.forEach(function (tab) {

                tab.active = $scope.active(tab.route);
            });
        });



        $scope.openBranchClose = function (closingBranch,  mode) {
            //set the state params so we can use thru out app
            $state.params.mode = mode;
            $state.params.closingBranch = closingBranch;
            $state.params.transfertoBranch = null;

            AdvBranchesService.postBranchClose(null);


        };
		$scope.marketDisplayInfo = {};
        $scope.instPageSize = 30;
        $scope.totalInstItems = 0;
        $scope.instItemsPerPage = 50;
        $scope.currentInstPage = 1;
        $scope.instPageCount = function () {
            return Math.ceil($scope.instData.length / $scope.instItemsPerPage);
        };

        // Need to get user friendly names from Ids
        $scope.branchId = $stateParams.branchId;

        $scope.openEditBranchForm = function (branchID, mode) {
            //set the state params so we can use thru out app
            $stateParams.mode = mode;
            $stateParams.branchId = branchID;

            AdvInstitutionsService.addOrEditBranch(branchID);


        };

        $scope.openEditGeocodeForm = function () {
            console.log('branchId ' + $scope.branchId);
            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: true,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/institutions/views/_BranchGeocode.html',
                controller: 'AdvInstitutionsEditBranchGeocodeController'
            });
        };

        activate();

        function activate() {

            // CRG - 04/21/2019 - This raises an error and I see no reason to have this call
            //$timeout(function () {
            //    $('[id="historyTransactionDate _input"]')[0].focus();
            
            //}, 750);

            window.scrollTo(0, 0);

            var params = {
                branchId: $scope.branchId
            };

            AdvBranchesService.getBranchDetail(params).then(function (result) {

                $scope.instData = result;
                var data = {
                    specialityFlagId: result.specialityFlagId
                                            
                };
                AdvBranchesService.getSpecialityFlag(data).then(function (result) {
                    $scope.specialityFlag = result;                    
                });  

                AdvInstitutionsService.getInstitutionData({ rssdId: $scope.instData.parentRssdId, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                    .then(function (result) {
                    $scope.instparent = result;
                    $scope.instDataReady = true;
                });
            });
            
        }

        $scope.printView = function(data, reportType) {
            var jData = angular.toJson(data);
            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }
    }
})();



(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionBranchDetailController', AdvInstitutionBranchDetailController);

    AdvInstitutionBranchDetailController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvBranchesService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants', '$window'];

    function AdvInstitutionBranchDetailController($scope, $state, $stateParams, $timeout, $templateCache, AdvBranchesService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants, $window) {



        activate();

        function activate() {

        }


        $scope.printView = function (data, reportType) {
            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        };

        $scope.openAddressGeocodeCompare = function (streetAddress, cityName, stateAbrv, zip, latitude, longitude) {
            var fullAdr = streetAddress + ", " + cityName + " " + stateAbrv + " " + zip;
            var mapUrl = "https://www.bing.com/maps?style=h&rtp=adr." + escape(fullAdr) + "~pos." + escape(latitude) + "_" + escape(longitude) + "_" + escape(latitude) + ",%20" + escape(longitude);
			window.open(mapUrl, "", "width=1400,height=800,scrollbars=yes,menubar=no,resizable=yes,status=no,toolbar=no,replace=true");
		}	
    }
})();


(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionBranchGeocodeController', AdvInstitutionBranchGeocodeController);

    AdvInstitutionBranchGeocodeController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvBranchesService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants'];

    function AdvInstitutionBranchGeocodeController($scope, $state, $stateParams, $timeout, $templateCache, AdvBranchesService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants) {

        $scope.openCensusGeoData = function (brLat, brLng) {
            if (isNaN(brLat) || isNaN(brLng)) { return; }
            var mapUrl = "https://geocoding.geo.census.gov/geocoder/geographies/coordinates?benchmark=4&vintage=4&x=" + escape(brLng) + "&y=" + escape(brLat);
            window.open(mapUrl, "", "width=750,height=900,scrollbars=yes,menubar=no,resizable=yes,status=no,toolbar=no,replace=true");
        }


        activate();

        function activate() {

        }
    }
})();


(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionBranchNearestController', AdvInstitutionBranchNearestController);

    AdvInstitutionBranchNearestController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', 'AdvBranchesService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants'];

    function AdvInstitutionBranchNearestController($scope, $state, $stateParams, $timeout, $templateCache, AdvInstitutionsService, AdvBranchesService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants) {




        $scope.toggleBranchTarget = function (branch) {

            branch.parentRssdId = Number(branch.parentOrg.rssdId);
           // branch.branchId = branch.id;

            AdvInstitutionsService.getNonHHIInstitutionsSearchData({ rssd: branch.parentOrg.rssdId }).then(function (result) {
                if (result) {
                    if (!UserData.institutions.findSavedInstitution(result[0]));
                    UserData.institutions.save(result[0]);
                    UserData.institutions.saveBranch(branch);
                }

            });

		}

		$scope.openBranchDistanceMap = function (siblingLat, siblingLng) {
			var startLat = $scope.$parent.instData.latitude;
			var startLng = $scope.$parent.instData.longitude;
			var mapUrl = "https://www.bing.com/maps?style=h&mode=d&rtop=1~1~0&rtp=pos." + escape(startLat) + "_" + escape(startLng) + "~pos." + escape(siblingLat) + "_" + escape(siblingLng);
			window.open(mapUrl, "", "width=1400,height=800,scrollbars=yes,menubar=no,resizable=yes,status=no,toolbar=no,replace=true");
		}

        $scope.openBranchCloseandDepositTransfer = function (closingBranch,transfertoBranch ,  mode, roadMiles) {
            //set the state params so we can use thru out app
            $state.params.mode = mode;
            $state.params.closingBranch = closingBranch;
            $state.params.transfertoBranch = transfertoBranch;
            $state.params.roadMiles = roadMiles;
            AdvBranchesService.postBranchClose(null);


        };

        $scope.isSavedBranch = function (branch) {
            branch.parentRssdId = Number(branch.parentOrg.rssdId);
            return UserData.institutions.isSavedBranch(branch);
        }


        activate();

        function activate() {

            AdvBranchesService.getNearestBranches($scope.branchId, 6).then(function (result) {

                $scope.nearestData = result;
                $scope.nearestDataReady = true;

            });

        }
        //$scope.printView = function () {
        //    var branchId = $scope.branchId;

        //    var data = [
        //        branchId
        //    ];
        //    var reportType = 'nearestBranches';

        //    var jData = angular.toJson(data);

        //    $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        //}
    }
})();





(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionBranchMapController', AdvInstitutionBranchMapController);

    AdvInstitutionBranchMapController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', 'AdvBranchesService', 'leafletData', 'leafletBoundsHelpers', 'MarketsService', 'MarketMapService', 'toastr', 'leafletMapEvents'];

    function AdvInstitutionBranchMapController($scope, $state, $stateParams, $timeout, $templateCache, AdvInstitutionsService, AdvBranchesService, leafletData, leafletBoundsHelpers, MarketsService, MarketMapService, toastr, leafletMapEvents) {

        $scope.marketMap = null;
        var branchData = null;
        var allBranchData = null;
        $scope.markers = [];
        var year = (new Date()).getFullYear();
        var mapBoxAndOpenMapsAttribution = '&copy;' + year + ' <a href="https://www.mapbox.com/about/maps/">MapBox</a> &copy;' + year + ' <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>';
        var cssAdded = false;

        $scope.toggleBranchTarget = function (branch) {

            branch.parentRssdId = Number(branch.parentOrg.rssdId);
            //branch.branchId = branch.id;

            AdvInstitutionsService.getNonHHIInstitutionsSearchData({ rssd: branch.parentOrg.rssdId }).then(function (result) {
                if (result) {
                    if (!UserData.institutions.findSavedInstitution(result[0]));
                    UserData.institutions.save(result[0]);
                    UserData.institutions.saveBranch(branch);
                }

            });

        }

        

        $scope.isSavedBranch = function (branch) {
            branch.parentRssdId = Number(branch.parentOrg.rssdId);
            return UserData.institutions.isSavedBranch(branch);
        }
        $scope.eventDetected = "No events yet...";

        angular.extend($scope, {
            printMap: printMap,
            leafletData: leafletData,
            mapReady: false,
            center: {},
            geoJson: {},
            layers: {
                overlays: {}
            },
            bounds: null,
            showBranches: false,
            toggleBranches: toggleBranches,
            showCounties: true, //affects map style
            showCities: true, //affects map style
            showRoads: true, //affects map style
            setMapStyle: setMapStyle,
            showMarket: true,
            toggleMarket: toggleMarket,
            showOtherMarkets: false,
            toggleOtherMarkets: toggleOtherMarkets,
            showStates: false,
            toggleStates: toggleStates,
            markers: {},
            hoveredMarket: null,
            marketUndefined: false,
            mapStyles: {
                "CountiesRoadsCities": {
                    name: 'Counties, Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdk0r3001uganjch20akrs',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: true
                    }
                },
                "Counties": {
                    name: 'Counties Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhoaj50020ganjjg9cvcxi',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: false
                    }
                },
                "Roads": {
                    name: 'Roads Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhlhll001wg7ncl1gps309',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: false
                    }
                },
                "Cities": {
                    name: 'Cities Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdkdbp001gg8m4xzloqdl5',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: true
                    }
                },
                "CountiesRoads": {
                    name: 'Counties & Roads',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhsd0o001xg7nc6tkcbv4y',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: false
                    }
                },
                "RoadsCities": {
                    name: 'Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circddako001tganj2eqgiaph',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: true
                    }
                },
                "CountiesCities": {
                    name: 'Counties & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhhjbj001igfkvz8hqfkxe',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: true
                    }
                },
                "None": {
                    name: 'None',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'cirqcpxde002pg9nggrktu888',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: false
                    }
                }
            }
        });



        function refreshMarkers() {
            if ($scope.showBranches) {
                callBranches();
            }
        };

        activate();

        function activate() {

            if (!cssAdded) {
                // load in the print css
                cssAdded = true;
                var cssTag = document.createElement("link");
                cssTag.type = "text/css";
                cssTag.rel = "stylesheet";
                cssTag.href = "/content/css/mapPrint.css";
                document.getElementsByTagName("head")[0].appendChild(cssTag);
            }

            $scope.$watch('instData', function (dataLoaded) {
                if (dataLoaded) {
                    populateMap();
                }
            });

        }

        function printMap() {
            window.print();
        }

        function addPrintClass() {
            $("#leafy, #leafy *").addClass("printMap");
            $("#leafy *").addClass("printMapChild");
            $("#leafy").parent().addClass("printMapContainer");
            $("#mapPartsSelectBox ul, #mapPartsSelectBox ul *").addClass("printMap");
            $('body').wrapInner('<div id="printBodyWrap" />');
        }

        function populateMap() {
			$scope.$on("leafletDirectiveGeoJson.leafy.mouseout",
				function (ev, leafletPayload) {
					$scope.hoveredMarket = null;
				});

			$scope.$on('leafletDirectiveMap.leafy.dragend', function (event) {
				refreshMarkers();
			});

			$scope.$on('leafletDirectiveMap.leafy.zoomend', function (event) {
				refreshMarkers();
			});

			$scope.$on('leafletDirectiveMap.leafy.load', function (event) {
				addPrintClass();
			});

			$scope.$on("leafletDirectiveGeoJson.leafy.click", function (ev, leafletPayload) {
				var feature = leafletPayload.leafletObject.feature;
				$state.go("root.adv.markets.detail.definition", { market: feature.properties.marketId });
			});

			$scope.$on("leafletDirectiveGeoJson.leafy.mouseover",
				function (ev, leafletPayload) {

					var layer = leafletPayload.leafletEvent.target,
						feature = leafletPayload.leafletObject.feature;

					layer.setStyle({
						weight: 4,
						color: "#000",
						fillOpacity: 0.75
					});
					layer.bringToFront();

					$scope.hoveredMarket = feature.properties;
				});		

			setMapStyle();

            MarketsService.find($scope.instData.bankingMarketId, { getMap: true })
                .then(function (marketMap) {

					$scope.marketMap = marketMap.map;

					$scope.marketDisplayInfo = { 'name': $scope.instData.bankingMarket, 'description': '', 'marketId': $scope.instData.bankingMarketId};

                    var bounds = null;
                    if (marketMap.map.geoJson) {
                        bounds = leafletBoundsHelpers.createBoundsFromArray([
                            [marketMap.map.geoJson.bbox[1], marketMap.map.geoJson.bbox[0]],
                            [marketMap.map.geoJson.bbox[3], marketMap.map.geoJson.bbox[2]]
                        ]);
                        delete marketMap.map.geoJson.bbox;
                    }
                    $scope.bounds = bounds;
                    $scope.center = {};


                    AdvBranchesService.getNearestBranchesForMap($scope.branchId, 100, 100000, false).then(function (result) {

                        var data = {};
                        for (var i = 0; i < result.length; i++) {
                            var br = result[i];
                            data["m" + br.branchId] = {
                                branchId: br.branchId,
                                lat: br.latitude,
                                lng: br.longitude,
                                draggable: false,
                                message: "<a ui-sref='root.adv.institutions.summary.details({rssd: " + br.institutionRSSDId + "})'>" + br.institutionName + "</a><br/>" +
                                     (br.branchNum == 0 ? "<br/><span class='badge'>Head Office</span>" : '') + "<br/>" +
                                    "<a href='#' ui-sref='root.adv.institutions.branch.details({branchId: " + br.branchId + "})'>" + br.name + "</a><br/>" +
                                    "<small>" + br.streetAddress + "<br/>" + br.cityName + ", " + br.statePostalCode + " " + br.zipcode + "</small>",
                                getMessageScope: function () { return $scope; }

                            };
                        }

                        $scope.center = {
                            lat: $scope.instData.latitude,
                            lng: $scope.instData.longitude,
                            zoom: 10
                        }

                        data["m_home"] = {
                            branchId: $scope.instData.branchId,
                            lat: $scope.instData.latitude,
                            lng: $scope.instData.longitude,
                            icon: redIcon,
                            draggable: false,
                            message: "<a ui-sref='root.adv.institutions.summary.details({rssd: " + $scope.instData.parentRssdId + "})'>" + (result.length > 0 ? result[0].institutionName : '') + "</a><br/>" +
                                 ($scope.instData.facility == 0 ? "<br/><span class='badge'>Head Office</span>" : '') + "<br/>" +
                                "<a href='#' ui-sref='root.adv.institutions.branch.details({branchId: " + $scope.instData.branchId + "})'>" + $scope.instData.name + "</a><br/>" +
                                "<small>" + $scope.instData.address + "<br/>" + $scope.instData.city + ", " + $scope.instData.state + " " + $scope.instData.zip + "</small>",
                            getMessageScope: function () { return $scope; }

                        };

                        $scope.layers.overlays.market = {
                            name: "theMarket",
                            type: "geoJSONShape",
                            data: $scope.marketMap.geoJson,
                            layerOptions: {
                                style: {
                                    //fillColor: result.map.color || "#577492",
                                    fillColor: "blue",
                                    weight: 2,
                                    opacity: 1,
                                    color: 'white',
                                    dashArray: '3',
                                    fillOpacity: 0.2
								},

								onEachFeature: function (feature, layer) {
									layer.on('mouseover', function () {
										highlightViewedMarketMap(layer, true);
									});
									layer.on('mouseout', function () {
										highlightViewedMarketMap(layer, false);
									});
									layer.on('click', function () {
										$state.go("root.adv.markets.detail.definition", { market: $scope.instData.bankingMarketId });
									});
								}
							},							
                            visible: true,
                            layerParams: {
                                showOnSelector: false
                            }
                        };


                        branchData = data;
                        $scope.markers = data;
                        $scope.mapReady = true;

                        $scope.$on('leafletDirectiveMap.leafy.dragend', function (event) {
                            refreshMarkers();
                        });

                        $scope.$on('leafletDirectiveMap.leafy.zoomend', function (event) {
                            refreshMarkers();
                        });

                        $scope.$on('leafletDirectiveMap.leafy.load', function (event) {
                            addPrintClass();
						});										
                    });
                });
		}

		function highlightViewedMarketMap(layer, showHighlight) {
			if (showHighlight) {
				$timeout(function () {
					$scope.hideMapMarketLink = false;
					$scope.hoveredMarket = $scope.marketDisplayInfo;
					layer.setStyle({
						weight: 3,
						color: "#595959",
						fillOpacity: 0.6,
						opacity: 1
					});
					layer.bringToFront();
				}, 0); // use timeout to avoid race condition with mouse outs from surrounding market shape layers
			}
			else {
				// no timeout here. On the mouse out we want it to happen asap so we don't mess with any other mouse over events..
				$scope.hideMapMarketLink = false;
				$scope.hoveredMarket = null;
				layer.setStyle({
					weight: 2,
					color: "white",
					fillOpacity: 0.25
				});
			}
		}


        function MergeBranchSets(source, dest) {

            var result = [];

            _.each(source, function (e) {
                result.push(e);
            });

            _.each(dest, function (e) {
                if (!_.find(source, {branchId: e.branchId}))
                    result.push(e);
            });

            return result;
        }

        function callBranches() {
            leafletData.getMap()
                    .then(function (map) {

                        if (map._zoom > 7) {
                            var bounds = map.getBounds();

                $scope.gettingBranches = true;
                            AdvBranchesService
                                .getBranchesInRect(bounds.getNorthWest().lat,
                                    bounds.getNorthWest().lng,
                                    bounds.getSouthEast().lat,
                                    bounds.getSouthEast().lng) //caching at service layer
                    .then(function (result) {
                        var data = {};
                        for (var i = 0; i < result.length; i++) {
                            var br = result[i];
                            data["m" + br.branchId] = {
                                branchId: br.branchId,
                                lat: br.latitude,
                                lng: br.longitude,
                                draggable: false,
                                            icon: br.institutionRSSDId == $scope.instData.parentRssdId
                                                ? blueIcon
                                                : greenIcon,
                                            message: "<a ui-sref='root.adv.institutions.summary.details({rssd: " +
                                                br.institutionRSSDId +
                                                "})'>" +
                                                br.institutionName +
                                                "</a><br/>" +
                                                (br
                                                    .branchNum ==
                                                    0
                                                    ? "<br/><span class='badge'>Head Office</span>"
                                                    : '') +
                                                "<br/>" +
                                                "<a href='#' ui-sref='root.adv.institutions.branch.details({branchId: " +
                                                br.branchId +
                                                "})'>" +
                                                br.name +
                                                "</a><br/>" +
                                                "<small>" +
                                                br.streetAddress +
                                                "<br/>" +
                                                br.cityName +
                                                ", " +
                                                br.statePostalCode +
                                                " " +
                                                br.zipcode +
                                                "</small>",
                                getMessageScope: function () { return $scope; }

                            };
                        }
                   
                        allBranchData = data;
                        $scope.markers = MergeBranchSets(branchData, allBranchData);

                                    hasBranches = true;
                                    $scope.gettingBranches = false;
                                });

                        } else {
                            toastr.error("Could not retrieve branch data at this zoom level.", "Please zoom in futher and try again.");
                        }
                    });
        }
                        

        var hasBranches = false;
        function toggleBranches() {            
            $scope.showBranches = !$scope.showBranches;
            if ($scope.showBranches) {
                callBranches();
            } else {
                $scope.markers = branchData;
            }

        }

        var hasStates = false, statesGeo = null;
        function toggleStates() {
            if ($scope.noStateData) return false;
            if (hasStates) {
                $scope.geoJson = $scope.showStates ? statesGeo : {};
            } else {
                $scope.gettingStates = true;
                MarketMapService.getStates($scope.instData.bankingMarketId)
                    .then(function (result) {
                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                        }
                        else if (result.features.features.length == 0) {
                            $scope.noStateData = true;
                        }
                        else {
                            var colors = ["red", "yellow", "blue", "orange"],
                                colorIndex = 0;

                            var geoJson = {
                                data: result.features,
                                style: function (feature) {
                                    return {
                                        fillColor: colors[feature.id % colors.length],
                                        weight: 2,
                                        opacity: 0.5,
                                        color: "white",
                                        dashArray: "3",
                                        fillOpacity: 0.25
                                    }
                                },
                                resetStyleOnMouseout: true
                            };
                            $scope.geoJson = geoJson;
                            statesGeo = geoJson;
                            hasStates = true;
                        }

                        $scope.gettingStates = false;
                    });
            }
        }

        function toggleMarket() {
            $scope.layers.overlays.market.visible = $scope.showMarket;
        }

        var hasOtherMarkets = false, otherMarketsGeo = null;
        function toggleOtherMarkets() {
            if (hasOtherMarkets) {
                $scope.showOtherMarkets = !$scope.showOtherMarkets;
                $scope.geoJson = $scope.showOtherMarkets ? otherMarketsGeo : {};
            } else {
                $scope.gettingOtherMarkets = true;
                MarketMapService.getSurroundingMarkets($scope.instData.bankingMarketId)
                    .then(function (result) {

                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                            return;
                        }

                        var colors = ["red", "orange", "yellow", "green", "purple"];

                        var geoJson = {
                            data: result.features,
                            style: function (feature) {
                                return {
                                    fillColor: colors[feature.properties.index % colors.length],
                                    weight: 2,
                                    opacity: 0.5,
                                    color: "white",
                                    dashArray: "3",
                                    fillOpacity: 0.25
                                }
                            },
                            resetStyleOnMouseout: true
                        };
                        $scope.geoJson = geoJson;
                        otherMarketsGeo = geoJson;

                        hasOtherMarkets = true;
                        $scope.gettingOtherMarkets = false;
                    });
            }
        }



        function setMapStyle() {

            var tileSet = null;

            _.forEach($scope.mapStyles,
                function (t) {
                    if (t.data.counties === $scope.showCounties && t.data.cities === $scope.showCities && t.data.roads === $scope.showRoads) {
                        tileSet = t;
                        return false;
                    }
                });


            if (tileSet)
                $scope.tiles = tileSet;
        }
    }
})();

(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvInstitutionBranchMarketDistancesController', AdvInstitutionBranchMarketDistancesDetailController);

    AdvInstitutionBranchMarketDistancesDetailController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvBranchesService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants', '$window'];

    function AdvInstitutionBranchMarketDistancesDetailController($scope, $state, $stateParams, $timeout, $templateCache, AdvBranchesService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants, $window) {
        $scope.isWorking = false;
        $scope.distanceData = [];

        $scope.openBranchDistanceMap = function (startLat, startLng, endLat, endLng) {
            var mapUrl = "https://www.bing.com/maps?style=h&mode=d&rtop=1~1~0&rtp=pos." + escape(startLat) + "_" + escape(startLng) + "~pos." + escape(endLat) + "_" + escape(endLng);
            window.open(mapUrl, "", "width=1400,height=800,scrollbars=yes,menubar=no,resizable=yes,status=no,toolbar=no,replace=true");
        }

        activate();

        function activate() {
            $scope.isWorking = true;
            AdvBranchesService.getBranchToMarketBranchDistance($scope.$parent.branchId).then(function (result) {
                if (result) {
                    $scope.distanceData = result;
                    $scope.isWorking = false;
                }

            });
        }         
    }
})();

var blueIcon = {
    iconUrl: '/Content/leaflet/images/marker-icon.png',
    iconSize: [25, 41],
    iconAnchor: [25, 41],
    popupAnchor: [-3, -76],
    shadowUrl: '/Content/leaflet/images/marker-shadow.png',
    shadowSize: [41, 41],
    shadowAnchor: [25, 41]
};

var redIcon = {
    iconUrl: '/Content/leaflet/images/marker-icon-red.png',
    iconSize: [25, 41],
    iconAnchor: [25, 41],
    popupAnchor: [-3, -76],
    shadowUrl: '/Content/leaflet/images/marker-shadow.png',
    shadowSize: [41, 41],
    shadowAnchor: [25, 41]
};

var greenIcon = {
    iconUrl: '/Content/leaflet/images/marker-icon-green.png',
    iconSize: [25, 41],
    iconAnchor: [25, 41],
    popupAnchor: [-3, -76],
    shadowUrl: '/Content/leaflet/images/marker-shadow.png',
    shadowSize: [41, 41],
    shadowAnchor: [25, 41]
};


;






(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsDetailController', AdvInstitutionsDetailController);

    AdvInstitutionsDetailController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants'];

    function AdvInstitutionsDetailController($scope, $state, $stateParams, $timeout, $templateCache, AdvInstitutionsService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants) {
		$scope.orgEntityTypeCodeName = '';
		$scope.orgEntityCodes = [];
		$scope.orgEntityCodeName = ''
		
        activate();

		function activate() {
			AdvInstitutionsService.getOrgEntityTypeCodes().then(function (data) {
				$scope.orgEntityCodes  = data;
			});	          
		}


		$scope.getOrgEntityTypeDisplayName = function (orgEntityTypeId) {
			var objEntCode = _.find($scope.orgEntityCodes, { entityTypeId: orgEntityTypeId });
			if (!objEntCode) { return ''; }

			return objEntCode.entityTypeCode;
		}		
    }
})();





;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionDetailHistoryController', AdvInstitutionDetailHistoryController);

    AdvInstitutionDetailHistoryController.$inject = ['$scope', '$stateParams', 'AdvInstitutionsService', '$window', '$sce','$state','$uibModal'];

    function AdvInstitutionDetailHistoryController($scope, $stateParams, AdvInstitutionsService, $window, $sce, $state, $uibModal) {
        angular.extend($scope, {
            historyReady: false,
            filter: "all",
            filterYear: "all",
            institutionHistory:null,
            includeBranchTxns: true,
            showPublic: false,
            expand:true,
            branchTxnTypes: ["Openings", "Closings", "Sales", "Location Changes"],
            hasBranchTxnTypeFilter: function () {
                return _.indexOf(this.branchTxnTypes, this.filter) > -1
            },
            years: [],
            hasYearFilter: function () {
                return this.filterYear != 'all' && _.indexOf(this.years, this.filterYear) > -1;
            },
            checkNoResults: function () {
                return $scope.institution != null ? _.filter(_.flatMap($scope.institution.history, function (e) { return e.data }),
                        function (e) { return $scope.historyFilter(e) }).length == 0 : false;
            },
            setYearFilter: function (year) {
                //$scope.filter = year;
                $scope.filterYear = year;
                var yearChunk = _.find($scope.institution.history, { year: year });
                if (yearChunk)
                    yearChunk.isOpen = true;
            },
            showBranchTransactions: false,
            clearBranchTxnTypeFilter: function (showbranch) {
                $scope.showBranchTransactions = showbranch;
   
                if (!this.showBranchTransactions && this.hasBranchTxnTypeFilter()) {
                    this.filter = "all";
                }
            },
            historyFilter: function (hist) {
                var hasCorrectYear = $scope.filterYear == 'all' || $scope.filterYear == '' || $scope.filterYear == hist.year;

                if (!$scope.showBranchTransactions && (hist.isBranchOpening || hist.isBranchClosing || hist.isBranchSale || hist.isBranchRelocation)) {
                    return false;
                }

                if ($scope.filter == 'all')
                    return true && hasCorrectYear;
                if ($scope.filter == 'mergers')
                    return hist.isMerger && hasCorrectYear;
                if ($scope.filter == 'acquisitions')
                    return hist.isAcquisition && hasCorrectYear;
                if ($scope.filter == 'Openings')
                    return hist.isBranchOpening && hasCorrectYear;
                if ($scope.filter == 'allbranchtrans')
                    return hist.isBranch && hasCorrectYear;
                if ($scope.filter == 'Closings')
                    return hist.isBranchClosing && hasCorrectYear;
                if ($scope.filter == 'Sales')
                    return hist.isBranchSale && hasCorrectYear;
                if ($scope.filter == 'Location Changes')
                    return hist.isBranchRelocation && hasCorrectYear;
                if ($scope.filter == 'failures')
                    return hist.isFailure && hasCorrectYear;
                if ($scope.filter == 'misc')
                    return hist.isMisc && hasCorrectYear;
                if ($scope.filter == 'precassidi')
                    return hist.isPreCassidi && hasCorrectYear;
                return true;
            },
            closeOpenAllYearGroups: function (open) {
                $scope.expand = open;
                angular.forEach($scope.institution.history, function (obj, index) {
                    obj.isOpen = open === true ? true : open === false ? false : !obj.isOpen;
                });
            },
            loadHistory: function (isPublic) {
               
                if (isPublic && $scope.filter == 'precassidi') {
                    $scope.filter = 'all';
                }
                if ($scope.institutionHistory != null) {
                    $scope.showPublic = isPublic;
                    angular.forEach($scope.institutionHistory, function (val, key) {
                        if (val.isPreCassidi == false) {
                                var year = val.year;
                                if (_.indexOf($scope.years, year) == -1)
                                    $scope.years.push(year);
                                }
                    });

                    $scope.years.sort().reverse();

                    var historyByYear = [];

                    if (!isPublic) {
                        for (var i = 0; i < $scope.years.length; i++) {
                            var year = $scope.years[i];
                            var chunk = _.filter($scope.institutionHistory, { year: year });

                            historyByYear.push({ year: year, data: chunk });
                           }
                       var preCassidi = _.filter($scope.institutionHistory, {isPreCassidi: true});
                       if (preCassidi.length > 0) {
                               historyByYear.push({year : 'Pre-CASSIDI Footnote', data: preCassidi});
                       }
                    }
                    else {
                        for (var i = 0; i < $scope.years.length; i++) {
                            var year = $scope.years[i];
                            var chunk = _.filter($scope.institutionHistory, { year: year });
                            var publicChunck = [];

                            for (var x = 0; x < chunk.length; x++) {
                                if (chunk[x].publicMemoText != "") {
                                    publicChunck.push(chunk[x]);
                                }
                            }
                            historyByYear.push({ year: year, data: publicChunck });
                        }
                    }
                    //console.log(historyByYear);
                    $scope.institution.history = historyByYear;

                    $scope.historyReady = true;
                    //set the 
                    //set everything to be open
                    angular.forEach($scope.institution.history, function (obj, index) {
                        obj.isOpen = true;
                    });

                    //ok so got it to work, but really I have to call this method twice.  I dont like this but need it done.
                    $scope.clearBranchTxnTypeFilter(true);
                }
            }
        });

        var getDetail = false;
        var getBranches = false;
        var getOperatingMarkets = false;
        var getHistory = true;
        $scope.sortBy = 'city';
        $scope.asc = true;

        activate();

        function activate() {
            $scope.historyReady = false;
            $scope.showPublic = false;
            AdvInstitutionsService.getInstitutionData({ rssdId: $stateParams.rssd, getDetail: getDetail, getBranches: getBranches, getOperatingMarkets: getOperatingMarkets, getHistory: getHistory }).then(function (result) {
                if ($scope.institution)
                    $scope.institution.history = result.history;
                else
                    $scope.institution = result;
                buildDetailsLink(result);
                $scope.institutionHistory = result.history;

                angular.forEach(result.history, function (val, key) {

                    if (!val.isPreCassidi) {
                        var year = val.year;

                        if(_.indexOf($scope.years, year) == -1)
                            $scope.years.push(year);
                       }
                });

                $scope.years.sort().reverse();

                var historyByYear =[];
                for (var i = 0; i < $scope.years.length; i++) {
                    var year = $scope.years[i];
                    var chunk = _.filter(result.history, {
                        year: year
                    });

                    historyByYear.push({ year: year, data: chunk });

                }
                var preCassidi = _.filter(result.history, { isPreCassidi: true });
                if (preCassidi.length > 0) {
                   historyByYear.push({ year: 'Pre-CASSIDI Footnote', data: preCassidi });
                }
                //console.log(historyByYear);
                $scope.institution.history = historyByYear;

                $scope.historyReady = true;
                //set the 
                //set everything to be open
                angular.forEach($scope.institution.history, function (obj, index) {
                    obj.isOpen = true;
                });

                //ok so got it to work, but really I have to call this method twice.  I dont like this but need it done.
                $scope.clearBranchTxnTypeFilter(true);
                $scope.clearBranchTxnTypeFilter(true);

            });


        }
        function buildDetailsLink(result) {
            var memoArray = [];
            var linkTitle;
            for (var i = 0; i < result.history.length; i++) {
                result.history[i].memo = $sce.trustAsHtml(result.history[i].memo.replace('--- Custom Memo:', '\n'));
                result.history[i].publicMemo = $sce.trustAsHtml(result.history[i].publicMemo);

            }
        }


        $scope.printView = function (data, reportType) {
            data.push($scope.sortBy);
            data.push($scope.asc);
            data.push($scope.showPublic);
            data.push($scope.filter);
            // Code change for update for reports when you can filter by Year and one of that other push button filters
            // data.push($scope.yearFilter); .....
            // This change will work in conjunction with Note put in the ReportBuilder for this update.

            data.push($scope.filterYear);
            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

        };





        $scope.openGetEditHistoryForm = function (historyId) {
            $state.params.historyId = historyId;
            $uibModal.open({
                animation: true,
                modal: true,
                backdrop: false,
                size: 'lg',
                templateUrl: 'AppJs/advanced/history/views/editInstHistoryTransaction.html',
                controller: 'AdvEditHistoryInstitution'
            }).result.then(function (result) {
                if (result == "done")
                    activate();
            });
        };
        $scope.openGetDeleteHistoryForm = function (historyId) {
            $state.params.historyId = historyId;
            $uibModal.open({
                animation: true,
                modal: true,
                backdrop: false,
                size: 'lg',
                templateUrl: 'AppJs/advanced/history/views/delInstHistoryTransaction.html',
                controller: 'AdvDeleteHistoryInstitution'
            }).result.then(function (result) {
                if (result == "done")
                     activate();
            });
        };
		$scope.showChangeRecDoc = function (docUrl) {
			if (!docUrl || docUrl == "") {
				return false;
			}
			var winWidth = window.innerWidth * 0.75;
			var winHeight = window.innerHeight * 0.8;
			var recordDocWin = window.open(docUrl, 'recordDocWin', 'location=yes,height=' + winHeight + ',width=' + winWidth + ',scrollbars=yes,status=yes');
			return false;
		}

    }

})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionDetailOpMarketController', AdvInstitutionDetailOpMarketController);

    AdvInstitutionDetailOpMarketController.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'AdvInstitutionsService', 'UserData', 'uiGridConstants', 'leafletBoundsHelpers', '$window'];

    function AdvInstitutionDetailOpMarketController($rootScope, $scope, $state, $stateParams, AdvInstitutionsService, UserData, uiGridConstants, leafletBoundsHelpers, $window) {
        var getDetail = true;
        var getBranches = false;
        var getOperatingMarkets = true;
        var getHistory = false;
        var instPageSize = 30;

        $scope.institution = null;
        $scope.institutionLoaded = false;

        activate();

        function activate() {
            AdvInstitutionsService.getInstitutionData({ rssdId: $stateParams.rssd, getDetail: getDetail, getBranches: getBranches, getOperatingMarkets: getOperatingMarkets, getHistory: getHistory }).then(function (result) {
                if ($scope.institution)
                    $scope.institution.definition = results.definition;
                else
                    $scope.institution = result;


                //check to see if we are an inst or tophold
                if ($scope.institution.definition.class == 'BANK' || $scope.institution.definition.class == 'THRIFT')
                {
                    $scope.showentity = false;
                }
                else
                {
                    $scope.showentity = true;
                }

                $scope.marketsData = result.markets;

                $scope.marketItemsLoaded = true;
            });
        }

        $scope.showClearLink = function () {
            return UserData.markets.any($scope.marketsData);
        };
        $scope.clearMarkets = function () {
            UserData.markets.remove($scope.marketsData);
        }


        $scope.printView = function (data, reportType) {
            data.push(document.getElementById('quickSearch').value);
            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

        };
    }

    angular
      .module('app')
        .filter('OperatingMktFilter', function () {
            return function (dataArray, searchTerm) {
                if (!dataArray) return;
                if (searchTerm.$ == undefined) {
                    return dataArray
                } else {
                    var term = searchTerm.$.toLowerCase();
                    return dataArray.filter(function (item) {
                        return checkVal(item.marketName, term)
                            || checkVal(item.marketId.toString(), term);
                    });
                }
            }

            function checkVal(val, term) {
                if (val == null || val == undefined)
                    return false;

                return val.toLowerCase().indexOf(term) > -1;
            }
        });

})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionDetailOrgsController', AdvInstitutionDetailOrgsController);

    AdvInstitutionDetailOrgsController.$inject = ['$scope', '$stateParams', '$state', 'AdvInstitutionsService', 'UserData', '$window','$timeout'];

    function AdvInstitutionDetailOrgsController($scope, $stateParams, $state, AdvInstitutionsService, UserData, $window, $timeout) {

        var getDetail = true;
        var getBranches = true;
        var getOperatingMarkets = false;
        var getHistory = false;
        $scope.instData = [];
        $scope.institutionLoaded = false;
        $scope.instPageSize = 30;
        $scope.instNoData = false;
        $scope.sortBy = 'city';
        $scope.asc = true;
        $scope.copyOfbranches = [];

        $scope.toggleBranchTarget = function (branch) {

            branch.parentRssdId = Number($stateParams.rssd);

            AdvInstitutionsService.getNonHHIInstitutionsSearchData({ rssd: branch.parentRssdId }).then(function (result) {
                if (result) {
                    if (!UserData.institutions.findSavedInstitution(result[0]));
                    UserData.institutions.save(result[0]);
                    UserData.institutions.saveBranch(branch);
                }

            });

        }

        $scope.isSavedBranch = function (branch) {
            branch.parentRssdId = Number($stateParams.rssd);
            return UserData.institutions.isSavedBranch(branch);
        }

        $scope.toggleTarget = function (inst) {


            AdvInstitutionsService.getNonHHIInstitutionsSearchData({ rssd: inst.rssdId }).then(function (result) {
                if (result) {
                    UserData.institutions.save(result[0]);
                }

            });

        }

        $scope.isSaved = function (inst) {
            return UserData.institutions.isSaved(inst);
        }



        activate();

        function activate() {
            
            AdvInstitutionsService.getInstitutionData({ rssdId: $stateParams.rssd, getDetail: getDetail, getBranches: getBranches, getOperatingMarkets: getOperatingMarkets, getHistory: getHistory }).then(function (result) {
                if (result.definition != null) {
                    $scope.instData = result.definition;
                    $scope.totalInstItems = $scope.instData.orgs.length;
                    $scope.instItemsPerPage = 50;
                    $scope.currentInstPage = 1;
                    $scope.instPageCount = function () {
                        return Math.ceil($scope.instData.orgs.length / $scope.instItemsPerPage);
                    };
                    $scope.totalInstItems = $scope.instData.orgs.length;
                    $scope.instDataPages = _.chunk($scope.instData.orgs, $scope.instItemsPerPage);


                }

                if (result.branches != null) {
                    $scope.branches = result.branches;
                    $scope.copyOfbranches = result.branches;
                    $scope.bItemsPerPage = 50;
                    $scope.currentBPage = 1;
                    $scope.bPageCount = function () {
                        return Math.ceil($scope.branches.length / $scope.bItemsPerPage);
                    };
                    if ($scope.branches != null) {
                        $scope.totalBranchItems = $scope.branches.length;
                        $scope.branchDataPages = _.chunk($scope.branches, $scope.bItemsPerPage);
                    }

                }
                if ($scope.instData.orgType == "Institution") {
                    $scope.criteria.cityFilter = true;
                }
                else {
                    $scope.criteria.cityFilter = false;
                }

                $scope.instNoData = ($scope.instData.orgs.length == 0 && $scope.branches.length == 0);
                $scope.institutionLoaded = true;
            });

        }

        // This is for the Sentinal directive to capture sort column
        $scope.applyChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.sortBy = sortBy.sort.predicate;
                $scope.asc = !sortBy.sort.reverse;
            } else {
                $scope.sortBy = 'city';
                $scope.asc = true;
            }
        }

        $scope.printView = function (data, reportType) {
            if ($scope.instData.orgs.length > 0 || $scope.branches.length > 0) {
            data.push(document.getElementById('quickSearch').value);
            data.push($scope.sortBy);
            data.push($scope.asc);
            data.push($scope.criteria.cityFilter);
            } else {
                data.push('');
                data.push($scope.sortBy);
                data.push($scope.asc);
                data.push(false);
            }

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        };



    }


    angular
  .module('app')
    .filter('branchFilter', function () {
        return function (dataArray, searchTerm) {
            var value = document.getElementById("chkCityFilter").checked;
            if (!dataArray) return;
            if (searchTerm.$ == undefined) {
                return dataArray
            } else {
                var term = searchTerm.$.toLowerCase();
                if (value) {
                    if (term.length == 1) {
                        return dataArray.filter(function (item) {
                            return checkFirstValue(item.city, term)
                        });
                    }
                    else {
                        return dataArray.filter(function (item) {
                            return checkVal(item.city, term)
                        });
                    }
                }
                else {
                    return dataArray.filter(function (item) {
                        return checkVal(item.name, term)
                            || checkVal(item.county, term)
                            || checkVal(item.city, term)
                    });
                }
            }
        }
        function checkFirstValue(val, term) {
            if (val == null || val == undefined)
                return false;
            return val.toLowerCase().charAt(0) == term;
        }
        function checkVal(val, term) {
            if (val == null || val == undefined)
                return false;

            return val.toLowerCase().indexOf(term) > -1;
        }
    });

    angular
  .module('app')
    .filter('orgFilter', function () {
        return function (dataArray, searchTerm) {
            if (!dataArray) return;
            if (searchTerm.$ == undefined) {
                return dataArray
            } else {
                var term = searchTerm.$.toLowerCase();
                return dataArray.filter(function (item) {
                    return checkVal(item.name, term)
                        || checkVal(item.county, term)
                        || checkVal(item.city, term)
                        || checkVal(item.rssdId.toString(), term)
                });
            }
        }

        function checkVal(val, term) {
            if (val == null || val == undefined)
                return false;

            return val.toLowerCase().indexOf(term) > -1;
        }
    });

})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionDetailPendingController', AdvInstitutionDetailPendingController);

    AdvInstitutionDetailPendingController.$inject = ['$scope', '$stateParams', 'AdvInstitutionsService', '$window'];

    function AdvInstitutionDetailPendingController($scope, $stateParams, AdvInstitutionsService, $window) {
        $scope.runDate = new Date();
        $scope.survivorRssdId = $stateParams.rssd;
        activate();

        function activate() {
            AdvInstitutionsService.getPendingByRssdId({ survivorRssdId: $stateParams.rssd }).then(function (result) {
                if (result.length > 0) {
                    $scope.PendingData = result;
                    $scope.pendingReady = true;
                }
                else {
                    $scope.pendingReady = false;
                }
                $scope.pending = true;
            });
        }

        $scope.printView = function (data) {
            data.push('');
            data.push(false);
            data.push('survivorName');
            data.push(true);
            data.push('');
           
            var reportType = 'pendingtransactionsinst';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');





            //var jData = angular.toJson(data);

            //$window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        };
    }


})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsPrintController', AdvInstitutionsPrintController);

    AdvInstitutionsPrintController.$inject = ['$scope', '$state', '$stateParams', '$timeout', '$templateCache', 'AdvInstitutionsService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants'];

    function AdvInstitutionsPrintController($scope, $state, $stateParams, $timeout, $templateCache, AdvInstitutionsService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants) {
        var getDetail = true;
        var getBranches = true;
        var getOperatingMarkets = false;
        var getHistory = false;
        $scope.instData = [];
        $scope.institutionLoaded = false;


        activate();

        function activate() {

            AdvInstitutionsService.getInstitutionData({ rssdId: $state.params.rssd, getDetail: getDetail, getBranches: getBranches, getOperatingMarkets: getOperatingMarkets, getHistory: getHistory }).then(function (result) {
                if (result && result.definition != null) {
                    $scope.instData = result;
                    $scope.rssd = $state.params.rssd;
                    $scope.instDataReady = true;
                    $scope.todaysDate = new Date();
                    $scope.hideEditDiv = true;


                    $scope.institutionLoaded = true;
                }
            });
        }








    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvInstitutionsSummaryController', AdvInstitutionsSummaryController);

    AdvInstitutionsSummaryController.$inject = ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$templateCache', '$uibModal', 'AdvInstitutionsService', 'UserData', 'StatesService', 'uiGridConstants', 'uiGridGroupingConstants', 'toastr', '$log', '$window'];

    function AdvInstitutionsSummaryController($scope, $rootScope, $state, $stateParams, $timeout, $templateCache, $uibModal, AdvInstitutionsService, UserData, StatesService, uiGridConstants, uiGridGroupingConstants, toastr, $log, $window) {
        var getDetail = true;
        var getBranches = false;
        var getOperatingMarkets = false;
        var getHistory = false;
        $scope.showPublic = false;
        $scope.failure = false;
        $scope.topholdStateCount = 0;

        $scope.instData = [];
        $scope.hasInst = false;
        $scope.institutionLoaded = false;
        $scope.tabs = [
                      { heading: "Details", route: "root.adv.institutions.summary.details", active: false },
                      { heading: "Subsidiary Institutions", route: "root.adv.institutions.summary.orgs", active: false },
                      { heading: "Operating Markets", route: "root.adv.institutions.summary.markets", active: false },
                      { heading: "History", route: "root.adv.institutions.summary.history", active: false },
                      { heading: "Pending", route: "root.adv.institutions.summary.pending", active: false }
        ];
        $scope.go = function (route) {
            var data = {
                rssd: $state.params.rssd
            };
            $state.go(route, data);
        };
        $scope.active = function (route) {
            return $state.is(route);
        };
        //$scope.goBack = function () {
        //    window.history.back(-historyBack);
        //}
        $scope.$on("$stateChangeSuccess", function () {
            $scope.tabs.forEach(function (tab) {
                if(tab != null)
                    tab.active = $scope.active(tab.route);
            });
        });



        $scope.openEditForm = function (rssdId, mode, parentRSSD) {
            //set the state params so we can use thru out app
            $state.params.mode = mode;
            $state.params.parentRSSD = parentRSSD;
            $state.params.rssdId = rssdId;
            $state.params.rssd = rssdId;

            if (mode == 'AddBank' || mode == 'AddThrift') {
                AdvInstitutionsService.addOrEditInstitution(rssdId);
            }
            else {
                if ($scope.instData.orgType == 'Tophold') {
                    AdvInstitutionsService.addOrEditTophold(rssdId);
                }
                else {
                    AdvInstitutionsService.addOrEditInstitution(rssdId);
                }
            }
        }





        $scope.openEditBranchForm = function (ParentRSSDID, criteria, mode) {
            //set the state params so we can use thru out app
            $state.params.mode = mode;
            $state.params.BankRSSDID = ParentRSSDID;
            $state.params.Bankcriteria = criteria;

            AdvInstitutionsService.addOrEditBranch(null);


        };


        $scope.printView = function (data, reportType) {
            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

        };


        $scope.openAddTopholdForm = function () {
            AdvInstitutionsService.addOrEditTophold();
        }

        $scope.openAddInstitutionForm = function () {
            $scope.showCancel = false;
            AdvInstitutionsService.addOrEditInstitution();
        }

        activate();

        function activate() {

            window.scrollTo(0, 0);

            // did we get here because an FDIC cert search failed?
            if($state.params.fdicNotFound)
            {
                $scope.failure = true;
                $scope.displayType = "fdic";
                $scope.instDataReady = true;
                $scope.failedFdic = $state.params.fdic;
                return;
            }

            $rootScope.isInWizard = false;
            AdvInstitutionsService.getPendingByRssdId({ survivorRssdId: $stateParams.rssd }).then(function (result) {
                if (result.length > 0) {
                    $scope.tabs[4].heading = "Pending (" + result.length + ")";
                }
                else {
                    $scope.tabs[4] = null;
                }

                AdvInstitutionsService.getRegulators().then(function (result) {
                    $scope.regulators = result;
                });

            AdvInstitutionsService.getInstitutionData({ rssdId: $state.params.rssd, getDetail: getDetail, getBranches: getBranches, getOperatingMarkets: getOperatingMarkets, getHistory: getHistory }).then(function (result) {
                if (result && result.definition != null) {
                    $scope.instData = result.definition;
                    $scope.totalInstItems = $scope.instData.orgs.length;
                    $scope.hasInst = true;
                    $scope.rssd = $state.params.rssd;
                    $scope.instItemsPerPage = 50;
                    $scope.currentInstPage = 1;
                    $scope.instPageCount = function () {
                        return Math.ceil($scope.instData.orgs.length / $scope.instItemsPerPage);
                    };

                    if ($scope.instData.orgType == "Tophold") {
                        AdvInstitutionsService.getTopholdBusStateCount($scope.rssd).then(function (returnedVal) {
                            $scope.topholdStateCount = returnedVal;
                        });
                    }

                    $scope.regulator = _.find($scope.regulators, { regulatorId: $scope.instData.regulatorId });


                    $scope.totalInstItems = $scope.instData.orgs.length;
                    $scope.instDataPages = _.chunk($scope.instData.orgs, $scope.instItemsPerPage);
                    $scope.instDataReady = true;

                    if ($scope.instData.rssdId == $scope.instData.parentId && ($scope.instData.class != "THRIFT" && $scope.instData.class != "BANK" && $scope.instData.class != "OTHER" && $scope.instData.class != "CSA THRIFT")) {
                        $scope.tabs[1].heading = "Subsidiary Institutions (" + $scope.instData.orgs.length + ")";
                    }
                    else {
                        $scope.tabs[1].heading = "Branches (" + $scope.instData.branchCount + ")";
                    }

                    $scope.header = "";
                    if ($scope.instData.orgType == "Tophold") {
                        $scope.header = "Tophold";
                    }
                    else if ($scope.instData.class == "BANK" && $scope.instData.branchCount > 0) {
                        $scope.header = "Bank Parent";
                    }
                    else if ($scope.instData.class == "BANK" && $scope.instData.branchCount == 0) {
                        $scope.header = "Bank";
                    }
                    else if ($scope.instData.class == "THRIFT" && $scope.instData.branchCount > 0) {
                        $scope.header = "Thrift Parent";
                    }
                    else if ($scope.instData.class == "THRIFT" && $scope.instData.branchCount > 0) {
                        $scope.header = "Thrift";
                    }

                    }
                    else {
                        // look for history record if no active record found
                        AdvInstitutionsService.getInstitutionHistoryData({ rssdId: $state.params.rssd }).then(function (result) {

                            if (result) {
                                $state.go('root.adv.history.insthistory', { rssdId: $state.params.rssd });
                }
                            else {
                                $scope.failure = true;
                                $scope.instDataReady = true;
                                $scope.failedRssd = $state.params.rssd;
                }

                $scope.institutionLoaded = true;
            });



                        $scope.hasInst = false;
                    }
                    $scope.institutionLoaded = true;

                });
                        });



        }

        $scope.saveRssdID = function () {

            AdvInstitutionsService
                .getNonHHIInstitutionsSearchData({ rssd: $scope.instData.rssdId })
                .then(function (result) {
                    if (angular.isArray(result) && result.length == 1) {
                        UserData.institutions.save(result[0]);
                    }
                });

        };
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('advCustomMarketController', advCustomMarketController);

    advCustomMarketController.$inject = ['$scope', 'AdvMarketsService', '$state', 'StatesService', 'AuthService', 'Dialogger','toastr','$window'];



    function advCustomMarketController($scope, AdvMarketsService, $state, StatesService, Auth, Dialogger, toastr, $window) {
        $scope.hiddeCriteria = false;
        $scope.renameField = false;
        $scope.LoadName = true;
        $scope.loaded = false;
        $scope.counties = [];
        $scope.user = Auth.details;
        $scope.editingMarketId = 0;
        activate();

        function activate()
        {
            window.scrollTo(0, 0);
            LoadData();
           
        }
        function LoadData() {
            $scope.loaded = false;
            AdvMarketsService.GetCustomMarkets().then(function (result) {
                var customMarketList = result;
                $scope.customMarkets = result;
                setStates($scope.customMarkets);
               
                $scope.loaded = true;
            });
        }
        function setStates(data) {
            for (var i = 0; i < data.length; i++) {
                data[i].states = _.join(_.flatMap(data[i].states, "name", ", ")).replace(/,/g, ", ");
               // data[i].states = data[i].states.replace(/,/g," , ");
                data[i].counties = _.join(_.flatMap(data[i].counties, "name", ", ")).replace(/,/g,", ");
             }
        }
        function buildMarkets(data) {
            var newData = [];

            for (var i = 0; i < data.length; i++) {
                var rec = data[i];
                for (var x = 0; x < rec.marketParts.length; x++) {
                    var county = { countyName: rec.marketParts[x].countyName };
                    var state = { stateName: rec.marketParts[x].stateName };
                    var cmarket = _.find(newData, { customMarketId: rec.customMarketId });
                    if (typeof cmarket == "undefined") {
                        cmarket = {
                            name: rec.name,
                            states: [state],
                            customMarketId: rec.customMarketId,
                            counties: [county]
                        };
                        newData.push(cmarket);
                    }
                    else {
                        var countyExits = _.find(cmarket.counties, { countyName: county.countyName });
                        if (typeof countyExits == "undefined"){
                            cmarket.counties.push(county);
                        }
                        var stateExists = _.find(cmarket.stateName, { stateName: state.stateName });
                        if (typeof stateExists == "undefined") {
                            cmarket.states.push(state);
                        }
                    }
                }
               
            }
            $scope.customMarkets = newData;
            $scope.loaded = true;
        }


        $scope.renameMarket = function (marketId, name)
        {
            $scope.criteria.name = name;
            $scope.editingMarketId = marketId;
            $scope.renameField = true;;

        }
        $scope.renameMarketCancel = function (marketId) {

            $scope.criteria.name = null;
            $scope.editingMarketId = 0;
            $scope.renameField = false;
        

        }
        $scope.newCustomMarket = function () {

            $state.go("^.CustomMarketDetails");              
        }
        $scope.displayCriteria = function (value) {
            $scope.hiddeCriteria = !value;

        }

        $scope.deleteCustomMarket = function (customMarketID, name)
        {

            var confirmDialog = Dialogger
                .confirm("Are you sure you want to delete the " + name + " Custom Market?");
              
            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    AdvMarketsService
                        .deleteCustomMarket(customMarketID)
                        .then(function (data) {
                            if (!data.errorFlag) {
                                toastr.success("Custom Market " + name +  " was deleted successfully!");
                                LoadData();
                            } else {
                                toastr.error("There was an unexpected error.",
                                    data
                                    .messageTextItems[0] ||
                                    "Please try again or contact support. Sorry about that.");
                            }
                        });
                } else
                    var value = confirmed;
            });

        }


        $scope.deleteAllCustomMarket = function ()
        {



        }

        $scope.renameCustomMarket = function () {
            var data = {
                customMarketId: $scope.editingMarketId,
                marketParts: [],
                name: $scope.criteria.name,
                userId: $scope.user.userId
            }
            AdvMarketsService.UpdateCustomMarket(data).then(function (result) {
                if (!result.errorFlag) {
                    $scope.criteria.name = null;
                    $scope.editingMarketId = 0;
                    $scope.renameField = false;
                    LoadData();
                }
            });
        }
        function CustomMarketPartsCount(data) {

        }

    }
})();

;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('advCustomMarketDetailsController', advCustomMarketDetailsController);

    advCustomMarketDetailsController.$inject = ['$scope', 'AdvMarketsService', '$window', '$state', 'StatesService', '$stateParams', 'AuthService', 'toastr', 'Dialogger'];
    

    function advCustomMarketDetailsController($scope, AdvMarketsService, $window, $state, StatesService, $stateParams, Auth, toastr, Dialogger) {
        $scope.criteria = [];
        $scope.customMarkets = [];
        $scope.copyOfCustomMarkets = [];
        $scope.hiddeNewCustom = false;
        $scope.NewCustomMarket = false;
        $scope.criteria.listCityAndSubdivisions = false;
        $scope.editingMarketId = 0;
        $scope.criteria.counties = [];
        $scope.lisOfCounties = [];
        $scope.lisOfCities = [];
        $scope.originalData = [];
        $scope.totalCitiesByCounty = [];
        $scope.totalSubdivisionsByCounty = [];
        $scope.lisOfCityAndSubdivisions = [];
        $scope.customMarketParts = [];
        $scope.criteria.cities = [];
        $scope.criteria.cityIds = [];
        $scope.criteria.subdivisions = [];
        $scope.criteria.subdivisionIds = [];
        $scope.customMarketView = [];
        $scope.counties = [];
        $scope.cities = [];
        $scope.subdivisions = [];
        $scope.loaded = false;
        $scope.tabs = [];
        $scope.user = Auth.details;
        $scope.customMarketPartId = 0;
        $scope.tabStateFIPSId = 0;
        $scope.StateAutoAddedSplitCity = false;
        $scope.criteria.noBranches = false;

        activate();

        function activate() {
            window.scrollTo(0, 0);
            $scope.newMarketStart = true;
            var customMarketList = [];
            var data = {
                includeDC: true,
                includeTerritories: true
            };
            StatesService.getStateSummaries(data).then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });


            loadData();
        }
        function loadData() {
            var marketId = $stateParams.marketId;
            ClearVariables();

            if (marketId == "") {
                $scope.NewCustomMarket = true;
                $scope.loaded = true;
            }
            else {
                $scope.NewCustomMarket = false;                
                AdvMarketsService.GetCustomMarketById(marketId).then(function (result) {
                    $scope.NewCustomMarket = false;
                    $scope.originalData = result;
                    var data = result;

                    if (data.marketParts != null) {                   
                        loadTabsMarkert(data.marketParts);
                        loadCustomMarketView(data);
                    }
                    else {
                        $scope.tabs = [];          
                        $scope.loaded = true;
                    }
                });
            }
           
        }
        function loadTabsMarkert(data) {
            var tabHeading = [];
            $scope.tabs = [];
            var count = 0;
            
            for (var i = 0; i < data.length; i++)
            {
                var state = data[i].stateName;
                var isAutoAddedSplitCity = (data[i].isAutoAddedSplitCity == null ? false : data[i].isAutoAddedSplitCity);
                if (isAutoAddedSplitCity)
                    count += count + 1;

                if (i == 0) {
                    $scope.tabStateFIPSId = ($scope.tabStateFIPSId == 0 ? data[i].stateFIPSId : $scope.tabStateFIPSId);
                }

                tabHeading = { heading: (isAutoAddedSplitCity ? state + " **" : state), value: data[i].stateFIPSId, active: ($scope.tabStateFIPSId == data[i].stateFIPSId ? true : false), isAutoAddedSplitCity: isAutoAddedSplitCity };
                var existsState = _.find($scope.tabs, { value: data[i].stateFIPSId });
                if (typeof existsState == "undefined") {
                    $scope.tabs.push(tabHeading);
                }
               
            }
         
            var validateState = _.find($scope.tabs, { value: $scope.tabStateFIPSId });
            if (typeof validateState == "undefined") {
                  
                $scope.tabStateFIPSId = $scope.tabs[0].value;
                $scope.tabs[0].active = true;

            }
            if (count > 0)
                $scope.StateAutoAddedSplitCity = true;
            else
                $scope.StateAutoAddedSplitCity = false;

            
        }
        function loadCustomMarketView(data) {

            var cityPartsByCounty = [];
            var marketParts = [];
            var subdivisionPartsByCounty = [];
            var customMarketId;
            var userId;
            var name;

            cityPartsByCounty = _.filter(data.cityPartsByCounty, { stateFIPSId: $scope.tabStateFIPSId });
            marketParts = _.filter(data.marketParts, { stateFIPSId: $scope.tabStateFIPSId });
            subdivisionPartsByCounty = _.filter(data.subdivisionPartsByCounty, { stateFIPSId: $scope.tabStateFIPSId });
            customMarketId = data.customMarketId;
            userId = data.userId;
            name = data.name;

            var data = {
                cityPartsByCounty: cityPartsByCounty,
                marketParts: marketParts,
                subdivisionPartsByCounty: subdivisionPartsByCounty,
                customMarketId: customMarketId,
                userId: userId,
                name: name
            }
            $scope.customMarketView = data;
            $scope.loaded = true;            
        }

        function ClearVariables() {
            $scope.criteria.cities = [];
            $scope.criteria.subdivisions = [];
            $scope.criteria.counties = [];
            $scope.criteria.state = null;
            $scope.lisOfCities = [];
            $scope.lisOfCounties = [];
            $scope.lisOfCityAndSubdivisions = [];
            if ($scope.criteria.listCityAndSubdivisions)
                $scope.criteria.listCityAndSubdivisions = !$scope.criteria.listCityAndSubdivisions;
        }
        function ValidateState() {
            var validateState = _.find($scope.tabs, { value: $scope.criteria.state.fipsId });
            if (typeof validateState == "undefined") {
                $scope.tabStateFIPSId = $scope.criteria.state.fipsId;
            }
        }
        $scope.newCustomMarketAdd = function () {

            $state.go("^.CustomMarketDetails({ marketId: '' })");
        }
        $scope.AddNewCustomMarketName = function () {
            var name = $scope.criteria.name;
            
            AdvMarketsService.AddCustomMarket(name).then(function (result) {
                if (!result.errorFlag) {
                    $scope.criteria.name = null;
                    $scope.editingMarketId = result.resultObject.customMarketId;
                    toastr.success("Custom Market " + name + " was added successfully!");
                    $state.go("^.CustomMarketDetails", { marketId: $scope.editingMarketId });
                    loadData();
                }
                else {
                    toastr.error(result.messageTextItems[0]);
                }
            });
        }
        $scope.isCitySelected = function (data, cityId) {
            var value = false;

            if( _.find(data.cityParts, { cityId: cityId }))
                 value = true;
           
            return value;
            
        }
        $scope.isAutoAddedSplitCity = function (data, cityId) {
            var value = false;

            if (_.find(data.cityParts, {cityId: cityId, isAutoAddedSplitCity: true }))
                value = true;

            return value;

        }
        $scope.deleteCounty = function (countyId, name) {
           
            var countyId = countyId;
            var customMarketId = $stateParams.marketId;
            var confirmDialog = Dialogger
               .confirm("Are you sure you want to delete " + name + " county.......");

            var data = {
                countyId: countyId,
                customMarketId: customMarketId
            };

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    $scope.loaded = false;
                    AdvMarketsService
                        .DeleteCustomMarketCounty(data)
                        .then(function (result) {
                            if (!data.errorFlag) {
                                toastr.success("County " + name + " was deleted successfully!");
                                loadData();
                            } else {
                                toastr.error("There was an unexpected error.",
                                    result
                                    .messageTextItems[0] ||
                                    "Please try again or contact support.");
                            }
                        });
                } else
                    var value = confirmed;
            });

        }
        $scope.addRemoveSubdivision = function (data, CountySubDivisionId, name) {
            $scope.loaded = false;
            var arr = $scope.originalData.subdivisionPartsByCounty;
            var subdivision;

            for (var i = 0; i < arr.length; i++) {
                var sub = arr[i].countySubdivisionParts;

                if (_.find(sub, { countySubDivisionId: CountySubDivisionId, countyId: data.countyId })) {

                    var subdivision = _.find(sub, { countySubDivisionId: CountySubDivisionId, countyId: data.countyId });
                }
            }

            if (subdivision) {
                    var data = {
                        CustomMarketId: subdivision.customMarketId,
                        CustomMarketPartId: subdivision.customMarketPartId
                    };
                    AdvMarketsService.DeleteCustomMarketPart(data).then(function (result) {
                        if (!result.errorFlag) {
                            $scope.SubSelectedByCounty = [];
                            toastr.success("Subdivision " + name + " was deleted successfully!");
                            loadData();
                        }
                    });
            }
            else {
                var data = {
                    CountySubDivisionId: CountySubDivisionId,
                    CountyId: data.countyId,
                    CountySubdivision: null,
                    CustomMarketId: data.customMarketId,
                    CustomMarketPartId: null,
                    IsAutoAddedSplitCity: false
                };
                AdvMarketsService.AddCustomMarketPart(data).then(function (result) {
                    if (!result.errorFlag) {
                        $scope.SubSelectedByCounty = [];
                        toastr.success("Subdivision " + name + " was added successfully!");
                        loadData();
                    }
                });
            }

        }
        $scope.addRemoveCity = function (data, cityId, name) {
            $scope.loaded = false;
            var countyId = data.countyId;
           // var customMarketPartId = data.customMarketPartId;
            var customMarketId = data.customMarketId;
            var value = false;

            if (_.find(data.cityParts, { cityId: cityId })) {

                var part = _.find(data.cityParts, { cityId: cityId });

                var data = {          
                    CustomMarketId: part.customMarketId,
                    CustomMarketPartId: part.customMarketPartId,

                };
                AdvMarketsService.DeleteCustomMarketPart(data).then(function (result) {
                    if (!result.errorFlag) {
                        $scope.SubSelectedByCounty = [];
                        toastr.success("City " + name + " was deleted successfully!");
                        loadData();
                    }
                });
            }
            else {

                var data = {
                    CityId: cityId,
                    CountyId: countyId,
                    CountySubdivision: null,
                    CustomMarketId: customMarketId,
                    CustomMarketPartId: null,
                    IsAutoAddedSplitCity: false
                };
                //var data = {
                //    CustomMarketId: customMarketId,
                //};
                AdvMarketsService.AddCustomMarketPart(data).then(function (result) {
                    if (!result.errorFlag) {
                        $scope.SubSelectedByCounty = [];
                        toastr.success("City " + name + " was added successfully!");
                        loadData();
                    }
                });
            }
        }
        $scope.addNewParts = function () {
            $scope.loaded = false;
            var customMarketId = $stateParams.marketId;
            var cityIds = [];
            var countySubdivisionIds = [];
    
            for (var i = 0; i < $scope.criteria.cities.length; i++) {
                var cityId = $scope.criteria.cities[i].cityId;
                cityIds.push(cityId);
            }
            for (var i = 0; i < $scope.criteria.subdivisions.length; i++) {
                var countySubdivisionId = $scope.criteria.subdivisions[i].countySubdivisionId;
                countySubdivisionIds.push(countySubdivisionId);
            }

            var data = {
                cityIds: cityIds,
                countySubdivisionIds: countySubdivisionIds,
                customMarketId: customMarketId
            };
            AdvMarketsService.AddCustomMarketParts(data).then(function (result) {
                if (!result.errorFlag) {
                    ValidateState();
                    loadData();
                }
            });

        }
        $scope.addNewCountyParts = function () {
            $scope.loaded = false;
            var count = $scope.criteria.counties.length;
            var error = false;
            var counties = [];

            for (var i = 0; i < $scope.criteria.counties.length; i++) {
                var countyId = $scope.criteria.counties[i].countyId;
                var customMarketId = $stateParams.marketId;
                counties.push(countyId);
            }
            var data = {
                cityIds: null,
                countyIds: counties,
                countySubdivisionIds: null,
                customMarketId: customMarketId

            };

            AdvMarketsService.AddCustomMarketCountyParts(data).then(function (result) {
                if (!result.errorFlag) {
                    $scope.SubSelectedByCounty = [];
                    toastr.success("Custom market part(s) added successfully!");
                    ValidateState();
                    loadData();
                }
            });

        }
        $scope.getCustomMarketById = function () {
            var marketId = $scope.criteria.customMarketID.marketId;

            AdvMarketsService.GetCustomMarketById(marketId).then(function (result) {
                $scope.customMarketParts = result;

            });

        }
        $scope.isSubSelected = function (county,countySubdivisionId) {
            var value = false;
            var arr = $scope.originalData.subdivisionPartsByCounty;
            

            for (var i = 0; i < arr.length; i++) {
                var sub = arr[i].countySubdivisionParts;
                if (_.find(sub, { countySubDivisionId: countySubdivisionId })) {
                    var countyId = county.countyId;
                    value = true;
                    break;
                }
                  
            }    

            return value;
        }
        $scope.renameCustomMarket = function () {
            $scope.buildANewCustomMarket = true;

        }
        $scope.getSubdivisionCount = function (countyId) {
            var count = 0;

           // var sub = _.filter($scope.SubSelectedByCounty, { countyId: countyId });
            var sub =  _.filter($scope.originalData.subdivisionPartsByCounty, { countyId: countyId });

            if (sub.length > 0) {
                count = sub[0].countySubdivisionParts.length;
            }

            return count;
        }
        $scope.newCustomMarket = function () {

            $state.go("^.CustomMarketDetails");
        }
        $scope.displayCriteria = function (value) {
            $scope.hiddeCriteria = !value;

        }
        $scope.displayNewCustom = function (value) {
            $scope.hiddeNewCustom = !value;
        }
        $scope.displayCityAndSubdivisions = function (value) {
            $scope.criteria.listCityAndSubdivisions = !value;

            if ($scope.criteria.listCityAndSubdivisions) {
                var data = {
                    countyId: $scope.criteria.counties[0].countyId
                };
                StatesService.getCitySummaries(data).then(function (result) {
                    $scope.lisOfCities = result;
                });
                StatesService.getCountySubdivisionSummaries(data).then(function (result) {
                    $scope.lisOfCityAndSubdivisions = result;
                });
            }
            else {
                $scope.lisOfCities = null;
                $scope.lisOfCityAndSubdivisions = null;
            }
        }

        $scope.LoadNewCounties = function () {

            var stateFipsId = $scope.criteria.state.fipsId;
            $scope.criteria.noBranches = false;

            AdvMarketsService.checkStateBranches(stateFipsId).then(function (result) {
                if (result) {
                    LoadCounties();
                }
                else {
                    $scope.criteria.noBranches = true;
                }
            });



        }
        function LoadCounties() {
            if ($scope.criteria.state != null) {
                $scope.criteria.counties = [];
                $scope.lisOfCounties = [];
                var data = {
                    stateFIPSId: $scope.criteria.state.fipsId
                };
                StatesService.getCountySummaries(data).then(function (result) {
                    var newcounties = [];
                    for (var x = 0; x < result.length; x++) {
                        var rec = result[x];
                        var state = result[x].stateSummary.name;

                        newcounties = { countyId: rec.countyId, countyName: rec.countyName, state: state };
                        $scope.lisOfCounties.push(newcounties);

                    }
                });
            }
        }
        $scope.stateChange = function (data) {
            $scope.tabStateFIPSId = data;
            loadCustomMarketView($scope.originalData);
        }

        $scope.addCounty = function (countyId, countyName) {
            var idx = -1;
            var exists = false;

            if ($scope.criteria.counties.length > 0) {
                angular.forEach($scope.criteria.counties, function (val, key) {
                    if (!exists) {
                        if (val.countyId == countyId) {
                            idx = key;
                            exists = true;
                        }
                    }
                });
            }

            if (idx > -1) { // is currently selected
                $scope.criteria.counties.splice(idx, 1);
            } else { // is newly selected
                var data = {
                    countyId: countyId,
                    countyName: countyName
                };
                $scope.criteria.counties.push(data);

            }
            if ($scope.criteria.counties.length == 0) {
                $scope.criteria.cities = [];
                $scope.criteria.subdivisions = [];
                if ($scope.criteria.listCityAndSubdivisions)
                    $scope.criteria.listCityAndSubdivisions = !$scope.criteria.listCityAndSubdivisions;
            }
        }

        $scope.selectAllCities = function()
        {
            if ($scope.lisOfCities && $scope.lisOfCities.length > 0)
            {
                for (var i = 0; i < $scope.lisOfCities.length; i++)
                {
                    $scope.addCity($scope.lisOfCities[i].cityId, $scope.lisOfCities[i].name, true)
                }
            }
        }

        $scope.clearAllCities = function ()
        {
            $scope.criteria.cities = [];
            $scope.criteria.cityIds = [];
        }

        $scope.addCity = function (cityId, name, skipRemovalStep) {
            var idx = -1;
            var exists = false;


            if ($scope.criteria.cities.length > 0) {
                angular.forEach($scope.criteria.cities, function (val, key) {
                    if (!exists) {
                        if (val.cityId == cityId) {
                            idx = key;
                            exists = true;
                        }
                    }
                });
            }
            if (idx > -1) { // is currently selected
                if (!skipRemovalStep) {
                    $scope.criteria.cityIds.splice(idx, 1);
                    $scope.criteria.cities.splice(idx, 1);
                }
            } else { // is newly selected
                var data = {
                    cityId: cityId,
                    name: name
                };
                $scope.criteria.cityIds.push(data.cityId);
                $scope.criteria.cities.push(data);

            }


        }

        $scope.selectAllSubdivisions = function () {
            if ($scope.lisOfCityAndSubdivisions && $scope.lisOfCityAndSubdivisions.length > 0) {
                for (var i = 0; i < $scope.lisOfCityAndSubdivisions.length; i++) {
                    $scope.AddSubdivisions($scope.lisOfCityAndSubdivisions[i].countySubdivisionId, $scope.lisOfCityAndSubdivisions[i].name, true);
                }
            }
        }

        $scope.clearAllSubdivisions = function() {
            $scope.criteria.subdivisions = [];
            $scope.criteria.subdivisionIds = [];
        }


        $scope.AddSubdivisions = function (countySubdivisionId, name, skipRemovalStep) {
            var idx = -1;
            var exists = false;
           
            if ($scope.criteria.subdivisions.length > 0) {
                angular.forEach($scope.criteria.subdivisions, function (val, key) {
                    if (!exists) {
                        if (val.countySubdivisionId == countySubdivisionId) {
                            idx = key;
                            exists = true;
                        }
                    }
                });
            }

            if (idx > -1) { // is currently selected
                if (!skipRemovalStep) {
                    $scope.criteria.subdivisionIds.splice(idx, 1);
                    $scope.criteria.subdivisions.splice(idx, 1);
                }
            } else { // is newly selected
                var data = {
                    countySubdivisionId: countySubdivisionId,
                    name: name
                };
                $scope.criteria.subdivisionIds.push(data.countySubdivisionId);
                $scope.criteria.subdivisions.push(data);
            }

        }

        $scope.backToList = function () {
            $scope.closeList = true;
            $scope.buildANewCustomMarket = false;
            //we need to clean everything;
        }

        $scope.newCustomMarketDef = function () {
            var name = $scope.criteria.name;
            var data = {
                cities: null,
                counties: null,
                description: null,
                district: null,
                footNote: null,
                hasChain: false,
                marketId: 1111,
                name: name
            };

            $scope.customMarkets.push(data);
            $scope.buildANewCustomMarket = false;

        }

        
    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('advEditMarketController', advEditMarketController);

    advEditMarketController.$inject = ['$scope', '$rootScope', '$stateParams', '$state', 'StatesService', 'AdvMarketsService', '$log', 'Dialogger', 'toastr', 'uibDateParser',  '$timeout'];

    function advEditMarketController($scope, $rootScope, $stateParams , $state, StatesService, AdvMarketsService, $log, Dialogger, toastr, uibDateParser, $timeout) {
        $scope.marketAdded = false;
        $scope.marketchanged = false;
        $scope.marketDataReady = false;
        $scope.mktEditNumber = false;
        $scope.preMarket = [];

        $scope.saveChanges = function () {
            //do the validation no matter which way you are going
            $scope.contProcessing = true;

            var d = new Date();
            //verify we have transaction date, name, primary 
            if (!$scope.criteria.marketId || $scope.criteria.marketId < 0) {
                toastr.error("Market Number is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.marketName) {
                toastr.error("Market Name is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.editMarketDescr) {
                toastr.error("Market Description is required!");
                $scope.contProcessing = false;
            }

            if (!$scope.criteria.district) {
                toastr.error("Market District is required!");
                $scope.contProcessing = false;
            }

           
            
            //check to see if this is a delete, if it is then ask if they are sure
            if ($scope.mode == 'Del') {
                Dialogger.confirm('You are about to set the Market to Inactive. Do you want to continue?').then(function (result) {
                    $scope.contProcessing = result;
            if ($scope.contProcessing == true) {
                processchange();
            }
                });
            }
            else
            {
                if ($scope.contProcessing == true) {
                    processchange();
                }
            }
            


        };

        function processchange() {
            var data = {
                marketId: $scope.criteria.marketId,
                HasChain: $scope.criteria.isSetChains,
                marketName: $scope.criteria.marketName,
                description: $scope.criteria.editMarketDescr,
                FootNote: $scope.criteria.FootNote,
                districtId: $scope.criteria.district,
                TransactionMode: $scope.mode,
                ReviewedDate: $scope.criteria.ReviewedDate
            };

           AdvMarketsService.postAddEditMarketDefinition(data).then(function (results) {
               $log.info(results.data.errorFlag);
               if (!results.data.errorFlag) {
                   
                   $scope.marketAdd = false;
                   $scope.$parent.market = $scope.market;
                   $scope.criteria.marketId = results.data.marketViewModel.definition.marketId;
                   if ($scope.mode == 'Edit')
                   {
                       $scope.showMarketDetails = false;
                       $scope.marketchanged = true;
                       $log.info("Market Changed");
                       toastr.success("Market Transaction has been updated!");
                   }
                   else if ($scope.mode == 'Del') {
                       $scope.showMarketDetails = false;
                       $scope.marketDel = true;
                       $log.info("Market Deactivated");
                       toastr.success("Market Transaction has been set to Inactive!");
                   }
                   else
                   {
                      
                       toastr.success("Market definition added Succesfully!");
                      
                       $scope.showMarketDetails = false;
                       $scope.marketAdded = true;
                       $log.info("Market Add");
                       

                          
                       
                   }
                   $scope.marketDataReady = false;
               }
               else {
                   var errorMessage = [];
                   if (results.data.messageTextItems.length > 0) {
                       for (var i = 0; i < results.data.messageTextItems.length; i++) {
                           errorMessage.push(results.data.messageTextItems[i]);
                           $log.info(results.data.messageTextItems[i]);
                       }
                   }
                   toastr.error("Error updating Market.", errorMessage.join() || "Please try again or contact support. Sorry about that.");
               }

           }, function (err) {
               alert("Sorry. There was an error.");
           });

        }

        

        $scope.maxLengthCheck = function (object) {
            if (object.value.length > object.maxLength)
                object.value = object.value.slice(0, object.maxLength)
        };

        $scope.isNumeric = function (evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /[0-9]|\./; 
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
            }
        };




        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        // this is hacky, replace with better solution
        $scope.showCancel = function () {

            return !$rootScope.isInWizard && $scope.$dismiss != null;

        };


        $scope.showHistory = function () {

            $state.go('root.adv.history.add');

        };


        $scope.cancel = function () {

            $scope.$dismiss();
            $state.reload();
        };

        activate();

        function activate() {
            //move to the top of the screen and set focus on the RSSDID
            var marketId = 0;
           
            window.scrollTo(0, 0);

            if ($scope.$parent.$parent == null) {

                if ($scope.criteria) {
                    marketId = $scope.criteria.marketId ? $scope.criteria.marketId : $state.params.marketId;
                }
                else {
                    marketId = $state.params.marketId ? $state.params.marketId : $state.params.marketId;

                }
            }
            var criteria = [];
            $scope.criteria = [];
            
            if ($state.params.mode == 'edit')
            {
                var data = {
                    marketId: marketId,
                    getDefinition: true
                };
                AdvMarketsService.getMarketById(data).then(function (result) {
                    //$log.info("getMarketById", result.definition);
                    var criteria = result;
                    var preCriteria = result;
                    $scope.$parent.transactionMode = "Edit Market Definition";
                    $scope.mode = 'Edit';
                    $scope.showMarketDetails = true;
                    $scope.criteria.marketId = result.definition.marketId;
                    $scope.criteria.marketName = result.definition.name;
                    $scope.criteria.editMarketDescr = result.definition.description;
                    $scope.criteria.FootNote = result.definition.footNote;
                    $scope.criteria.district = result.definition.district;
                    $scope.criteria.isSetChains = result.definition.hasChain;
                    $scope.marketAdded = false;
                    $scope.marketchanged = false;
                    $scope.marketDataReady = true;
                    preCriteria = angular.copy(result);
                    $scope.preMarket = preCriteria.definition;
                    $scope.mktEditNumber = true;
                    $scope.criteria.ReviewedDate = result.definition.reviewedDate;
                });
            }
            else if ($state.params.mode == 'del')
            {
                $scope.mode = 'Del';
                $scope.$parent.transactionMode = "Deactivate a Market Definition";
                var data = {
                    marketId: marketId,
                    getDefinition: true
                };
                AdvMarketsService.getMarketById(data).then(function (result) {
                    //$log.info("getMarketById", result.definition);
                    var criteria = result;
                    var preCriteria = result;
                    $scope.marketreadonly = true;
                    $scope.marketDel = false;
                    $scope.showMarketDetails = true;
                    $scope.criteria.marketId = result.definition.marketId;
                    $scope.criteria.marketName = result.definition.name;
                    $scope.criteria.editMarketDescr = result.definition.description;
                    $scope.criteria.FootNote = result.definition.footNote;
                    $scope.criteria.district = result.definition.district;
                    $scope.criteria.isSetChains = result.definition.hasChain;
                    $scope.marketAdded = false;
                    $scope.marketchanged = false;
                    $scope.marketDataReady = true;
                    preCriteria = angular.copy(result);
                    $scope.preMarket = preCriteria.definition;
                    $scope.mktEditNumber = true;
                    $scope.criteria.ReviewedDate = result.definition.reviewedDate;
                });

            }
                //default to add if nothing is passed in
            else
            {
                $scope.$parent.transactionMode = "Add Market Definition";
                $scope.mode = 'Add';
                $scope.showMarketDetails = true
                $scope.marketAdded = false;
                $scope.marketchanged = false;
                $scope.marketDataReady = true;
                $scope.mktEditNumber = false;
                $scope.criteria.isSetChains = false;

            }
                


        }
             

        



    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketDetailController', AdvMarketDetailController);

    AdvMarketDetailController.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'AdvMarketsService', 'uiGridConstants', 'leafletBoundsHelpers','StatesService', '$window'];

    function AdvMarketDetailController($rootScope, $scope, $state, $stateParams, AdvMarketsService, uiGridConstants, leafletBoundsHelpers,StatesService, $window) {
		$scope.hasPartialCounty = false;

		$scope.tabs = [
            { heading: "Details", route: "root.adv.markets.detail.definition", active: false },
            { heading: "Operating Institutions", route: "root.adv.markets.detail.hhi", active: false },
            { heading: "Map", route: "root.adv.markets.detail.map", active: false },
            { heading: "History", route: "root.adv.markets.detail.history", active: false },
            { heading: "Pending", route: "root.adv.markets.detail.pending", active: false }

        ];      

        $scope.go = function (route) {
            $state.go(route);
        };
        $scope.active = function (route) {
            return $state.is(route);
        };
        $scope.$on("$stateChangeSuccess", function () {
            $scope.tabs.forEach(function (tab) {
                if(tab != null)
                   tab.active = $scope.active(tab.route);
            });
        });

        $scope.printMarketSummary = function () {
            var data = [$scope.market.definition.marketId]

            data.push($scope.citySortBy);
            data.push($scope.cityAsc);
            data.push($scope.countySortBy);
            data.push($scope.countyAsc);

            var jData = angular.toJson(data);
			$window.open('/reportserver/generateanddisplayreport?reportType=bankingmarketsummary' + '&params=' + jData, '_blank');            
        }

		$scope.isMultiMarket = function (countyId) {
			if ($scope.market.definitionAdv
				&& $scope.market.definitionAdv.multiMarketCountyIds
				&& $scope.market.definitionAdv.multiMarketCountyIds.indexOf
				&& $scope.market.definitionAdv.multiMarketCountyIds.indexOf(countyId) > -1) {
				$scope.hasPartialCounty = true;
				return true;
			}
			return false;
		}


        $scope.$parent.hideEditDiv = false;
        //$scope.$parent.$parent.marketName = null;
        $scope.market = null;
        $scope.marketLoaded = false;
        $scope.listOfCities = [];
        $scope.listOfCounties = [];
        $scope.numBranchesOverDepositCap = 0;
        $scope.instRssdOverDepositCap = [];

        activate();

        $scope.openEditMarketForm = function (market, mode) {
            $state.params.mode = mode;
            AdvMarketsService.addOrEditMarket(market, mode);
        }

        $scope.openDeleteMarketForm = function (market, mode) {
            AdvMarketsService.addOrEditMarket(market, mode);
        }

        function loadCountyView(data){
            angular.forEach(data.definitionAdv.counties, function (val, key) {
                //var county = { countyId: val.countyId, countyName: val.countyName, postalCode: val.stateSummary.postalCode, district: data.definitionAdv.district > 0 ? data.definitionAdv.district : val.districtId };
                var county = { countyId: val.countyId, countyName: val.countyName, postalCode: val.stateSummary.postalCode, district: val.districtId > 0 ? val.districtId : data.definitionAdv.district };

                var idx = _.find($scope.listOfCounties, { countyId : val.countyId});

                if (typeof idx == "undefined")
                    $scope.listOfCounties.push(county);
            });
            sort.arr.multisort($scope.listOfCounties,
            ['postalCode', 'countyName'],
            ['ASC', 'ASC']);
        }


        function activate() {
            //removed tab specific print for market details only print
            //$scope.registerTabPrintFunc();
            //removed tab specific print for market details only print

            $scope.marketLoaded = false;

            //numBranchesOverDepositCap
            AdvMarketsService.getMarketPendingById({ marketId: $stateParams.market, getPending: true }).then(function (result) {
                if (result.length > 0) {
                    $scope.tabs[4].heading = "Pending (" + result.length + ")";
                }
                else {
                    $scope.tabs[4] = null;
                }

                AdvMarketsService.getMarketByIdAdv({ marketId: $stateParams.market, getDefinition: true })
                    .then(function (result) {
                        // $scope.$parent.$parent.marketName = result.definition.name;

                        if ($scope.market)
                            $scope.market.definition = results.definition;
                        else
                            $scope.market = result;
                        loadCountyView($scope.market);
                        $scope.marketLoaded = true;
                    });
            });

            var data = {
                depositAmt: '1000.0',
                marketId: $stateParams.market
            };

            AdvMarketsService.getNumBranchesOverDepositAmt(data)
            .then(function (result) {
                $scope.numBranchesOverDepositCap = result;
            });

            AdvMarketsService.getRssdsWithBranchesOverDepositAmt(data)
                .then(function (result) {
                    $scope.instRssdOverDepositCap = result;
                });            
        }


        $scope.applyCityChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.citySortBy = sortBy.sort.predicate;
                $scope.cityAsc = !sortBy.sort.reverse;
            } else {
                $scope.citySortBy = 'name';
                $scope.cityAsc = true;
            }

        }


        $scope.applyCountyChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.countySortBy = sortBy.sort.predicate;
                $scope.countyAsc = !sortBy.sort.reverse;
            } else {
                $scope.countySortBy = 'countyName';
                $scope.countyAsc = true;
            }

        }


        $scope.printView = function (data, reportType) {
            data.push($scope.citySortBy);
            data.push($scope.cityAsc);
            data.push($scope.countySortBy);
            data.push($scope.countyAsc);

            var jData = angular.toJson(data);
            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }


        if (typeof sort == 'undefined') {
            var sort = {};
        }

        sort.arr = {
            /**
        * Function to sort multidimensional array
        * 
        * param {array} [arr] Source array
        * param {array} [columns] List of columns to sort
        * param {array} [order_by] List of directions (ASC, DESC)
        * returns {array}
        */
            multisort: function(arr, columns, order_by) {
                if (typeof columns == 'undefined') {
                    columns = []
                    for (var x = 0; x < arr[0].length; x++) {
                        columns.push(x);
                    }
                }

                if (typeof order_by == 'undefined') {
                    order_by = []
                    for (var x = 0; x < arr[0].length; x++) {
                        order_by.push('ASC');
                    }
                }

                function multisort_recursive(a, b, columns, order_by, index) {
                    var direction = order_by[index] == 'DESC' ? 1 : 0;

                    var is_numeric = !isNaN(+a[columns[index]] - +b[columns[index]]);

                    var x = is_numeric ? +a[columns[index]] : a[columns[index]].toLowerCase();
                    var y = is_numeric ? +b[columns[index]] : b[columns[index]].toLowerCase();

                    if (x < y) {
                        return direction == 0 ? -1 : 1;
                    }

                    if (x == y) {
                        return columns.length - 1 > index ? multisort_recursive(a, b, columns, order_by, index + 1) : 0;
                    }

                    return direction == 0 ? 1 : -1;
                }

                return arr.sort(function(a, b) {
                    return multisort_recursive(a, b, columns, order_by, 0);
                });
            }
        };
    }
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketDetailDefinitionController', AdvMarketDetailDefinitionController);

    AdvMarketDetailDefinitionController.$inject = ['$scope', '$stateParams', 'AdvMarketsService'];

    function AdvMarketDetailDefinitionController($scope, $stateParams, AdvMarketsService) {
        $scope.$parent.hideEditDiv = false;
        activate();



        function activate() {
        }
    }
})();;
(function () {
	'use strict';

	angular
      .module('app')
      .controller('AdvMarketDetailHhiController', AdvMarketDetailHhiController);

	AdvMarketDetailHhiController.$inject = ['$scope', '$stateParams', 'AdvMarketsService', 'genericService'];

	function AdvMarketDetailHhiController($scope, $stateParams, AdvMarketsService, genericService) {

		var hhiColDefs = [
                    { displayName: "Fed ID", field: "rssdId" },
                    { displayName: "Type", field: "class" },
                    { displayName: "Branches", field: "branchCount" },
                    { displayName: "Name", field: "name" },
                    { displayName: "City", field: "city" },
                    { displayName: "State", field: "stateCode" },
                    { displayName: "Weighted Deposits", field: "weightedDeposits" },
                    { displayName: "Weighted Rank", field: "weightedRank" },
                    { displayName: "Weighted Market Share", field: "weightedMarketShare" },
                    { displayName: "Unweighted Deposits", field: "unweightedDeposits" },
                    { displayName: "Unweighted Rank", field: "unweightedRank" },
                    { displayName: "Unweighted Market Share", field: "unweightedMarketShare" }
		];
		$scope.isArchiveData = false;
		$scope.lastStructChangeDate = '';
		$scope.sodDate = '';
		$scope.marketId = 0;
		$scope.hhiData = [];
		$scope.hhiDataReady = false;
		$scope.hhiGridOptions = {
			enableSorting: true,
			enableColumnMenus: false,
			columnDefs: hhiColDefs,
			data: "hhiData", //tells ui-grid to find its data at $scope.data
			onRegisterApi: function (gridApi) {
				$scope.hhiGridApi = gridApi;
			},
		};
		$scope.totalHhiItems = 0;
		$scope.hhiItemsPerPage = 10;
		$scope.currentHhiPage = 1;
		$scope.showCUPurchasedBankNote = false;
		$scope.hhiPageCount = function () {
			return Math.ceil($scope.hhiData.length / $scope.hhiItemsPerPage);
		};

		$scope.roundHHI = function (hhi) {
            
	        return hhi ? Math.round(hhi) : 0;
		};

        $scope.getTotalBranches = function() {
            return _.sumBy($scope.hhiData, function(e) { return e.branchCount; });
		}
		$scope.getTHBankType = function (th) {
			
			return th.class;
		};
		$scope.getInstBankType = function (inst) {
			
			if (inst.class == 'BANK') {
				return 'BANK';
			}
			else if (inst.class == 'THRIFT' && inst.hhiWeight == 1) {
				return 'CSA THRIFT';
			}
			else if (inst.class == 'THRIFT' && inst.hhiWeight != 1) {
				return 'THRIFT';
			}
			else {
				return inst.class;
			}
		};

		activate();

		function activate() {
		    AdvMarketsService.checkIfUsingArchive().then(function (result) {
		        $scope.isArchiveData = result;
		    });
		    AdvMarketsService.getLastArchiveHistoryDate().then(function (result) {
		        $scope.lastStructChangeDate = result;
		    });
		    genericService.getSodDate().then(function (result) {
		        $scope.sodDate = result;
		    });

			// check if we need to display the credit union purchased bank/thrift notice.
			AdvMarketsService.hasCUNonCUPurchase($stateParams.market).then(function (result) {
				$scope.showCUPurchasedBankNote = result;
			});

			AdvMarketsService.getMarketHhiById({ marketId: $stateParams.market, getHhi: true })
                .then(function (result) {
                	if ($scope.market)
                		$scope.market.hhi = result.hhi;
                	else
                	    $scope.market = result;

                	$scope.criteria.marketID = $stateParams.market;
                	$scope.criteria.regionType = 'bankingMarket';

			        $scope.hhiData = result.hhi.orgs;
                	$scope.marketId = $stateParams.market;
                	$scope.totalHhiItems = $scope.hhiData.length;
                	$scope.hhiDataPages = _.chunk($scope.hhiData, $scope.hhiItemsPerPage);
                	$scope.hhiDataReady = true;
			});
		}

	}
})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketDetailHistoryController', AdvMarketDetailHistoryController);

    AdvMarketDetailHistoryController.$inject = ['$scope','$state', '$stateParams', 'AdvMarketsService','$uibModal','$sce', '$window', '$timeout'];

    function AdvMarketDetailHistoryController($scope, $state, $stateParams, AdvMarketsService, $uibModal, $sce, $window, $timeout) {
        angular.extend($scope, {
            historyReady: false,
            marketName: "",
            marketHistory: null,
            filter: "all",
            filterYear: "all",
            marketId:$stateParams.market,
            expand: true,
            includeBranchTxns: true,
            showPublic: false,
            checkNoResults: function () {
                return $scope.market != null ? _.filter(_.flatMap($scope.market.history, function (e) { return e.data }),
                        function (e) { return $scope.historyFilter(e) }).length == 0 : false;
            },
            branchTxnTypes: ["Openings", "Closings", "Sales", "Location Changes"],
            hasBranchTxnTypeFilter: function () {
                return _.indexOf(this.branchTxnTypes, this.filter) > -1
            },
            years: [],
            hasYearFilter: function () {
                return this.filterYear != 'all' && _.indexOf(this.years, this.filterYear) > -1;
            },
            setYearFilter: function (year) {
                //$scope.filter = year;
                $scope.filterYear = year;
                var yearChunk = _.find($scope.market.history, { year: year });
                if (yearChunk) {
                    console.log(yearChunk);
                    yearChunk.isOpen = true;
                }

            },
            showBranchTransactions: true,

            clearBranchTxnTypeFilter: function (showbranch) {
                $scope.historyReady = false;
                $timeout(function () {
                    $scope.clearBranchTxnTypeFilterWrapped(showbranch);
                    $scope.historyReady = true;
                }, 200);
            },

            clearBranchTxnTypeFilterWrapped: function (showbranch) {
                $scope.showBranchTransactions = showbranch;
                if (!this.showBranchTransactions && this.hasBranchTxnTypeFilter()) {
                    this.filter = "all";
                }
            },

            historyFilter: function (hist) {
                var hasCorrectYear = $scope.filterYear == 'all' || $scope.filterYear == '' || $scope.filterYear == hist.year;

                if (!$scope.showBranchTransactions && (hist.isBranchOpening || hist.isBranchClosing || hist.isBranchSale || hist.isBranchRelocation)) {
                    return false;
                }

                if ($scope.filter == 'all')
                    return true && hasCorrectYear;
                if ($scope.filter == 'TopholdParent')
                    return hist.isTopholdAndInstitution && hasCorrectYear;
                if ($scope.filter == 'Openings')
                    return hist.isBranchOpening && hasCorrectYear;
                if ($scope.filter == 'Closings')
                    return hist.isBranchClosing && hasCorrectYear;
                if ($scope.filter == 'allbranchtrans')
                    return hist.isBranch && hasCorrectYear;
                if ($scope.filter == 'Sales')
                    return hist.isBranchSale && hasCorrectYear;
                if ($scope.filter == 'Location Changes')
                    return hist.isBranchRelocation && hasCorrectYear;
                if ($scope.filter == 'failures')
                    return hist.isFailure;
                if ($scope.filter == 'MarketDefintion')
                    return hist.isMarketDefinitionChange && hasCorrectYear;
                return true;
            },
            closeOpenAllYearGroups: function (open) {
                $scope.historyReady = false;
                $timeout(function () {
                    $scope.closeOpenAllYearGroupsWrapped(open);
                    $scope.historyReady = true;
                }, 200);
            },
            closeOpenAllYearGroupsWrapped: function (open) {
                $scope.expand = open;
                angular.forEach($scope.market.history, function (obj, index) {
                    obj.isOpen = open === true ? true : open === false ? false : !obj.isOpen;
                });
            },
            switchInternalPublic: function (isPublic) {
                $scope.historyReady = false;
                $timeout(function () {
                    $scope.loadHistory(isPublic);
                    $scope.historyReady = true;
                }, 200);
            },
            loadHistory: function (isPublic) {
                if ($scope.marketHistory != null) {
                    $scope.showPublic = isPublic;
                    angular.forEach($scope.marketHistory, function (val, key) {
                        var year = val.year;
                        if (_.indexOf($scope.years, year) == -1)
                            $scope.years.push(year);
                    });

                    $scope.years.sort().reverse();

                    var historyByYear = [];
                    if (!isPublic) {
                        for (var i = 0; i < $scope.years.length; i++) {
                            var year = $scope.years[i];
                            var chunk = _.filter($scope.marketHistory, { year: year });

                            historyByYear.push({ year: year, data: chunk, isOpen: true });
                        }
                    }
                    else {
                        for (var i = 0; i < $scope.years.length; i++) {
                            var year = $scope.years[i];
                            var chunk = _.filter($scope.marketHistory, { year: year });
                            var publicChunck = [];

                            for (var x = 0; x < chunk.length; x++) {
                                if (chunk[x].publicMemoText != "") {
                                    publicChunck.push(chunk[x]);
                                }
                            }
                            historyByYear.push({ year: year, data: publicChunck, isOpen: true });
                        }
                    }

                    console.log(historyByYear);
                    $scope.market.history = historyByYear;

                    //$scope.historyReady = true;
                }
            }
         });       
        
        activate();

        function activate() {
            $scope.historyReady = false;
            AdvMarketsService.getMarketHistoryById({ marketId: $stateParams.market, getHistory: true }).then(function (result) {
                if ($scope.market)
                    $scope.market.history = result.history;
                else
                    $scope.market = result;
                buildDetailsLink(result);
                $scope.marketHistory = result.history;

                $scope.marketName = result.definition.name;
                $scope.$parent.hideEditDiv = false;

                angular.forEach(result.history, function (val, key) {
                    var year = val.year;
                    if (_.indexOf($scope.years, year) == -1)
                        $scope.years.push(year);
                });

                $scope.years.sort().reverse();

                var historyByYear = [];
                for (var i = 0; i < $scope.years.length; i++) {
                    var year = $scope.years[i];
                    var chunk = _.filter(result.history, { year: year });

                    historyByYear.push({ year: year, data: chunk, isOpen: true });
                }
                console.log(historyByYear);
                $scope.market.history = historyByYear;

                $scope.historyReady = true;

            });
        }
        function buildDetailsLink(result) {
            var memoArray = [];
            var linkTitle;
            for (var i = 0; i < result.history.length; i++) {
                result.history[i].memo = $sce.trustAsHtml(result.history[i].memo);
                result.history[i].publicMemoText = $sce.trustAsHtml(result.history[i].publicMemoText);
            }
        }
        $scope.openGetHistoryForm = function (historyId) {
            $state.params.historyMemoId = historyId;
            $state.params.marketName = $scope.marketName;
            $uibModal.open({
                animation: true,
                modal: true,
                backdrop: false,
                size: 'lg',
                templateUrl: 'AppJs/advanced/history/views/editMarketHistoryTransaction.html',
                controller: 'AdvEditHistoryMarket'
            }).result.then(function (result) {
                if (result == "done")
                    activate();
            });
        };
        $scope.openGetDelHistoryForm = function (historyId) {
            $state.params.historyId = historyId;
            $state.params.marketName = $scope.marketName;
            $uibModal.open({
                animation: true,
                modal: true,
                backdrop: false,
                size: 'lg',
                templateUrl: 'AppJs/advanced/history/views/delMarketHistoryTransaction.html',
                controller: 'AdvDeleteHistoryMarket'
            }).result.then(function (result) {
                if (result == "done")
                    activate();
            });
        };

        $scope.printView = function () {
            var data = [
                $stateParams.market,
                $scope.showPublic,
                $scope.filter,
                $scope.showBranchTransactions
            // Code change for update for reports when you can filter by Year and one of that other push button filters
            // data.push($scope.yearFilter); .....
            // This change will work in conjunction with Note put in the ReportBuilder for this update.
            ];


            data.push($scope.filterYear);
            

            var reportType = 'markethistory';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }

        $scope.showChangeRecDoc = function (docUrl) {
            if (docUrl == "test") {
                return false;
            }
            var winWidth = window.innerWidth * 0.75;
            var winHeight = window.innerHeight * 0.8;
            var recordDocWin = window.open(docUrl, 'recordDocWin', 'location=yes,height=' + winHeight + ',width=' + winWidth + ',scrollbars=yes,status=yes');
            return false;
        }
        

    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('advMarketHHIDepositAnaysisController', advMarketHHIDepositAnaysisController);

	advMarketHHIDepositAnaysisController.$inject = ['$scope', '$stateParams', '$timeout', '$templateCache', '$window', 'AdvMarketsService', 'ProFormaService', 'toastr', 'AdvInstitutionsService', 'AdvBranchesService', 'StatesService', '$uibModal', '$sce', 'Dialogger', 'THRIFT_WEIGHT_RULE_IDS'];
    

	function advMarketHHIDepositAnaysisController($scope, $stateParams, $timeout, $templateCache, $window, AdvMarketsService, ProFormaService, toastr, AdvInstitutionsService, AdvBranchesService, StatesService, $uibModal, $sce, Dialogger, THRIFT_WEIGHT_RULE_IDS) {
        $scope.instData = [];
        $scope.instDataReady = false;
        $scope.instLoadData = false;
        $scope.showMarketNumbers = false;
        $scope.showMSA = false;
        $scope.showCustomNumbers = false;
        $scope.editweight = false;
        $scope.editDeposit = false;
        $scope.totalDeposits = 0;
        $scope.hhi = null;
        $scope.hhiOrig = null;
        $scope.calProfForma = false;
        $scope.searchInstString = '';
        $scope.showCalProForma = false;
        $scope.processingData = false;
        $scope.hhiMarket = null;
        $scope.runDate = new Date();
        $scope.errorList = [];
        $scope.showPostMerger = false;
        $scope.cbtMessage = '';
        $scope.bogusCities = [];
        $scope.newBogusInst = {};
        $scope.creditUnionCount = 0;
        $scope.activationComplete = false;
        $scope.exceedsAuthority = false;
        $scope.hasAppliedBogusInsts = false;
        $scope.hasNewChanges = false;
        $scope.isArchiveData = false;
		$scope.lastStructChangeDate = '';
		$scope.bogusOtherCount = 0;
		$scope.bogusCUCount = 0;
		$scope.divestToBank = null;
		$scope.divestToThrift = null;
		$scope.showDivestCalcResults = false;
		$scope.divestBankWorking = false;
		$scope.divestThriftWorking = false;
		$scope.thriftWeightRuleTypeId = THRIFT_WEIGHT_RULE_IDS.default;
		$scope.thriftWeightRuleFootnote = '';
		$scope.mktPicker = {};
        $scope.pendingTransCount = 0;
        $scope.showCUPurchasedBankNote = false;
        $scope.stateDepositCapPercent = 100;
        $scope.numBranchesOverDepositCap = 0;
        $scope.instRssdOverDepositCap = [];
        //$scope.overlappingStatesLabel = '';

        $scope.foundSurvivor = null;

		$scope.reportDetails = {
			market: null,
			state: null,
			msa: null,
			customMarket: null,
			nonmsa: null,
			dateRun: '',
			pendingTransCount: 0
		};


        angular.extend($scope, {
            THCData: [],
            hhiData: [],
            hhiDataReady: false,
            showData: false,
            totalHhiItems: 0,
            hhiItemsPerPage: 10,
            currentHhiPage: 1,
            hhiPageCount: getHhiPageCount,
            selections: ProFormaService.selections,
            hasBuyer: ProFormaService.hasBuyer,
            hasTarget: ProFormaService.hasTarget,
            hasAnySelection: ProFormaService.hasAnySelection,
            clearBuyer: ProFormaService.clearBuyer,
            clearTargets: clearTargets,
            HistorybyMarketDataLoaded: false,
            TopHoldClosedDataLoaded: true,
            gatherHHIDeposits: handleHHIDepositAnalysis
        });

        $scope.getInstType = function (inst) {

            if (inst.class == 'BANK') {
                return 'BANK';
            }
            else if (inst.entityType == 'THRIFT' && inst.weight == 1) {
                return 'CSA THRIFT';
            }
            else if (inst.entityType == 'THRIFT' && inst.weight != 1) {
                return 'THRIFT';
            }
            else {
                return inst.class;
            }
        };

        $scope.flagChanges = function (stateToSet) {
            $scope.hasNewChanges = stateToSet;
        }

        $scope.isChecked = function (seller, branch) {
            return _.includes(seller.checkModel, branch);
        };


        $scope.selectCheck = function (seller, branch, $event) {

            if ($scope.isChecked(seller, branch)) {
                _.remove(seller.checkModel, function (n) {
                    return n == branch;
                });
            } else {
                seller.checkModel.push(branch);
            }

            $event.stopPropagation();
            $event.target.blur();

            return false;
        };

		$scope.commitChanges = function (seller) {
			seller.branchNums = [];
            seller.branchNums = _.join(_.map(seller.checkModel, function (e) { return e.facility; }), ', ');
            seller.checkModel = [];
        };


        $scope.canChooseBranches = function (seller) {
			if (seller.rssdId && (
				($scope.criteria.regionType == 'bankingMarket' && $scope.criteria.marketID) ||
				($scope.criteria.regionType == 'msa' && $scope.criteria.msa != null) ||
				($scope.criteria.regionType == 'state' && $scope.criteria.state != null) ||
				($scope.criteria.regionType == 'customMarket' && $scope.criteria.customMarket != null))
				&& !$scope.hasMultipleMarkets() && $scope.foundSurvivor != null && ($scope.foundSurvivor.class == 'BANK' || $scope.foundSurvivor.class == 'THRIFT' || $scope.foundSurvivor.class == 'OTHER')
				&& seller.foundNonSurvivor != null && (seller.foundNonSurvivor.class == 'BANK' || seller.foundNonSurvivor.class == 'THRIFT' || seller.foundNonSurvivor.class == 'OTHER')
			) {
				$scope.criteria.branchNums = [];
				return true;
			}

            return false;
        };


        $scope.updateBranchListInst = function (inst) {
            if ($scope.criteria.regionType == 'bankingMarket' && $scope.criteria.marketID) {

                if (inst.lastRun == inst.rssdid + "marketID" + $scope.criteria.marketID) {
                    return;
                }

                inst.isLoading = true;

                AdvBranchesService.getBranchSearchData({ parentRssdId: inst.rssdid, marketNumber: $scope.criteria.marketID }).then(function (result) {
                    inst.lastRun = inst.rssdid + "marketID" + $scope.criteria.marketID;
                    $scope.rebuildList(inst, result);
                    inst.isLoading = false;
                });
            } else if ($scope.criteria.regionType == 'msa' && $scope.criteria.msa != null) {

                if (inst.lastRun == inst.rssdid + "msa" + $scope.criteria.msa.msaId) {
                    return;
                }

                inst.isLoading = true;

                AdvBranchesService.getBranchSearchData({ parentRssdId: inst.rssdid, msa: $scope.criteria.msa.msaId }).then(function (result) {
                    inst.lastRun = inst.rssdid + "msa" + $scope.criteria.msa.msaId;
                    $scope.rebuildList(inst, result);
                    inst.isLoading = false;
                });

            } else if ($scope.criteria.regionType == 'state' && $scope.criteria.state != null) {

                if (inst.lastRun == inst.rssdid + "state" + $scope.criteria.state.fipsId) {
                    return;
                }

                inst.isLoading = true;

                AdvBranchesService.getBranchSearchData({ parentRssdId: inst.rssdid, state: $scope.criteria.state.fipsId }).then(function (result) {
                    inst.lastRun = inst.rssdid + "msa" + $scope.criteria.state.fipsId;
                    $scope.rebuildList(inst, result);
                    inst.isLoading = false;
                });               

            } else if ($scope.criteria.regionType == 'customMarket' && $scope.criteria.customMarket != null) {

                if (inst.lastRun == inst.rssdid + "customMarketID" + $scope.criteria.customMarket.customMarketId) {
                    return;
                }

                inst.isLoading = true;

                AdvBranchesService.getBranchSearchData({ parentRssdId: inst.rssdid, customMarket: $scope.criteria.customMarket.customMarketId }).then(function (result) {
                    inst.lastRun = inst.rssdid + "customMarketID" + $scope.criteria.customMarket.customMarketId;
                    $scope.rebuildList(inst, result);
                    inst.isLoading = false;
                });
            }
        };


        $scope.updateBranchList = function (seller) {

            if (!seller.rssdId)
                return;

            var marketIds = $scope.criteria.marketID.replace(/ /g, "");

            if ($scope.criteria.regionType == 'bankingMarket' && marketIds) {

                if (seller.lastRun == seller.rssdId + "marketID" + marketIds) {
                    $scope.updateCheckModel(seller);
                    return;
                }


                seller.isLoading = true;


                if (marketIds.includes(',')) {

                    seller.lastRun = seller.rssdId + "marketID" + marketIds;
					seller.branchList = [];

                    var marketArray = _.filter(_.map(marketIds.split(","), function (v) { return Number(v); }), function (v) { return v > 0 });

                    _.each(marketArray, function (market) {

                        AdvBranchesService.getBranchSearchData({ parentRssdId: seller.rssdId, marketNumber: market }).then(function (result) {


                            _.each(result,
                                function (inst) {
                                    if (inst && inst.branches) {

                                        if (inst.branches.length > 0)
                                            seller.branchList = seller.branchList.concat(inst.branches);

                                        _.each(inst.orgs,
                                            function (org) {
                                                if (org.branches.length > 0)
                                                    seller.branchList = seller.branchList.concat(org.branches);
                                            });
                                    }
                                });



                            seller.isLoading = false;
                            $scope.updateCheckModel(seller);

                        });
                    });

                } else {

                    AdvBranchesService.getBranchSearchData({ parentRssdId: seller.rssdId, marketNumber: marketIds }).then(function (result) {
                        seller.lastRun = seller.rssdId + "marketID" + marketIds;
                        $scope.rebuildList(seller, result);
                        seller.isLoading = false;
                        $scope.updateCheckModel(seller);

                    });
                }




            } else if ($scope.criteria.regionType == 'msa' && $scope.criteria.msa != null) {

                if (seller.lastRun == seller.rssdId + "msa" + $scope.criteria.msa.msaId) {
                    $scope.updateCheckModel(seller);
                    return;
                }

                seller.isLoading = true;

                AdvBranchesService.getBranchSearchData({ parentRssdId: seller.rssdId, msa: $scope.criteria.msa.msaId }).then(function (result) {
                    seller.lastRun = seller.rssdId + "msa" + $scope.criteria.msa.msaId;
                    $scope.rebuildList(seller, result);
                    seller.isLoading = false;
                    $scope.updateCheckModel(seller);
                });

            } else if ($scope.criteria.regionType == 'state' && $scope.criteria.state != null) {

                if (seller.lastRun == seller.rssdId + "state" + $scope.criteria.state.fipsId) {
                    $scope.updateCheckModel(seller);
                    return;
                }

                seller.isLoading = true;

                AdvBranchesService.getBranchSearchData({ parentRssdId: seller.rssdId, state: $scope.criteria.state.fipsId }).then(function (result) {
                    seller.lastRun = seller.rssdId + "msa" + $scope.criteria.state.fipsId;
                    $scope.rebuildList(seller, result);
                    seller.isLoading = false;
                    $scope.updateCheckModel(seller);
                });

            } else if ($scope.criteria.regionType == 'customMarket' && $scope.criteria.customMarket != null) {

                if (seller.lastRun == seller.rssdId + "customMarketID" + $scope.criteria.customMarket.customMarketId) {
                    $scope.updateCheckModel(seller);
                    return;
                }

                seller.isLoading = true;

                AdvBranchesService.getBranchSearchData({ parentRssdId: seller.rssdId, customMarket: $scope.criteria.customMarket.customMarketId }).then(function (result) {
                    seller.lastRun = seller.rssdId + "customMarketID" + $scope.criteria.customMarket.customMarketId;
                    $scope.rebuildList(seller, result);
                    seller.isLoading = false;
                    $scope.updateCheckModel(seller);
                });
            }

        };

        $scope.rebuildList = function (seller, instList) {

            seller.branchList = [];

            _.each(instList,
                function (inst) {
                    if (inst && inst.branches) {

                        if (inst.branches.length > 0)
                            seller.branchList = seller.branchList.concat(inst.branches);

                        _.each(inst.orgs,
                            function (org) {
                                if (org.branches.length > 0)
                                    seller.branchList = seller.branchList.concat(org.branches);
                            });
                    }
                });

        };


        $scope.updateCheckModel = function (seller) {

			if (seller.isLoading) { return; }

			var currentNums = [];
			if (seller.branchNums.trim && seller.branchNums.trim() != '') {
				currentNums = _.map(_.split(seller.branchNums, ','), function (e) { return e == '' ? null : Number(e); });
			}

            seller.checkModel = _.filter(seller.branchList,
                function (e) {
                    return _.find(currentNums, function (cn) { return cn == e.facility }) != null;
                });
        };

        $scope.branchToggle = function (open, seller) {

            if (open) {
                $scope.updateBranchList(seller);
            }

        };

        $scope.branchToggleInst = function (open, inst) {

            if (open) {
                $scope.updateBranchListInst(inst);
            }

        };


        $scope.$watch('criteria.customMarket', function (newValue, oldValue) {
            if (oldValue != newValue) {
                _.each($scope.criteria.sellerRSSDIDs,
                    function (seller) {
                        seller.branchNums = '';
                        seller.branchList = [];
                        seller.lastRun = null;
                    });
            }
        }, true);

        $scope.$watch('criteria.msa', function (newValue, oldValue) {
            if (oldValue != newValue) {
                _.each($scope.criteria.sellerRSSDIDs,
                    function (seller) {
                        seller.branchNums = '';
                        seller.branchList = [];
                        seller.lastRun = null;
                    });
            }
        }, true);

        $scope.$watch('criteria.state', function (newValue, oldValue) {
            if (oldValue != newValue) {
                _.each($scope.criteria.sellerRSSDIDs,
                    function (seller) {
                        seller.branchNums = '';
                        seller.branchList = [];
                        seller.lastRun = null;
                    });
            }
        }, true);


        $scope.$watch('criteria.marketID', function (newValue, oldValue) {
            if (oldValue != newValue) {
                _.each($scope.criteria.sellerRSSDIDs,
                    function (seller) {
                        seller.branchNums = '';
                        seller.branchList = [];
                        seller.lastRun = null;
                    });
            }
        });


        $scope.$watch('criteria.regionType', function (newValue, oldValue) {
            if (oldValue != newValue) {

                $scope.criteria.customMarket = null;
                $scope.criteria.state = null;
                $scope.criteria.msa = null;
                $scope.criteria.marketID = '';

                _.each($scope.criteria.sellerRSSDIDs,
                    function (seller) {
                        seller.branchNums = '';
                        seller.branchList = [];
                        seller.lastRun = null;
                    });
            }
        });





        //0            # a zero
        //(\.\d+)?     # a dot and min 1 numeric digit - this is made optional by ?
        //|            # or
        //1\.0         # one, a dot and a zero
        $scope.onlydecimal = function (weightValue) {

            if (weightValue >= 0 && weightValue <= 1) {
                return weightValue;

            }
            else {
                toastr.error("The weight has to be between 0 and 1!");
                return 1;
            }



        }

        $scope.resetBogusInst = function () {

            $scope.newBogusInst = {
                rssdid: '',
                type: '',
                branchcount: 0,
                name: '',
                state: null,
                city: null,
                weight: 0,
                deposit: 0,
                nonmsaID: 0

            }

        }


        $scope.oneLine = function (inst) {
            return inst.entityType == 'I' || $scope.isBogusInst(inst);
        }

        $scope.removeBogusInst = function (inst) {
            $scope.flagChanges(true);
            $scope.model.instBogus = _.filter($scope.model.instBogus, function (e) { return e.rssdid != inst.rssdid; });
            if ($scope.model.instBogusRSSDIds && $scope.model.instBogusRSSDIds.length > 0) {
                $scope.model.instBogusRSSDIds = _.filter($scope.model.instBogusRSSDIds, function (e) { return e != inst.rssdid; });
            }
        };

        $scope.addCUInst = function () {
            // assemble the parameters for query
            var data = {
                marketID: $scope.criteria.marketID,
                msaID: $scope.criteria.msa == null ? null : $scope.criteria.msa.msaId,
                stateId: $scope.criteria.state == null ? null : $scope.criteria.state.fipsId,
                nonmsaID: $scope.criteria.nonmsa == null ? null : $scope.criteria.nonmsa.nonMSAId,
                custommarkets: $scope.criteria
                    .customMarket ==
                    null
                    ? null
                    : $scope.criteria.customMarket.customMarketId,
                blnbankandthrift: $scope.criteria.reportType == 'BankandThrift',
                buyer: $scope.criteria.buyerRSSDID,
                targets: _.map(_.filter($scope.criteria.sellerRSSDIDs,
                    function (e) { return e.rssdId != null && e.rssdId != ''; }),
                    'rssdId').join(","),
                branches: getBranchIds($scope.criteria.sellerRSSDIDs).join(",")
            };

            AdvMarketsService.getCreditUnionsForHHI(data).then(function (result) {
                var numCUs = result.length;
                // check for duplicate RSSDId
                var dupRSSDIds = [];
                for (var i = 0; i < numCUs; i++) {
                    var rssdToTest = result[i].rssdid.toString();
                    if ($scope.model.instBogusRSSDIds.indexOf(rssdToTest) != -1) {
                        dupRSSDIds.push(rssdToTest);
                    }
                }

                if (dupRSSDIds.length > 0) {
                    var dupRSSDString = dupRSSDIds.join(", ");
                    Dialogger.alert('The following RSSD Ids have already been entered as "Additional Institutions". To load the credit unions, you must remove these RSSD Ids from "Additional Institutions." <br /><br /> RSSD Id(s): ' + dupRSSDString, 'ERROR: Duplicate RSSD Id(s)');
                    return;
                }

                for (var i = 0; i < numCUs; i++) {
                    $scope.addBogusInst(result[i]);
                }
            });

            //for (var i = 0; i < 4; i++) {
            //    var abc = {
            //        rssdid: (1 + i),
            //        type: 'CU',
            //        branchcount: 6,
            //        name: 'Test CU Branch ' + i,
            //        state: { fipsId: 29, isStateEquiv: false, name: 'Missouri', postalCode: 'MO', tigerId: null },
            //        city: { cityId: 0, countyId: 0, countySummary: null, name: 'My Town' },
            //        weight: 0,
            //        deposit: (10.321 * i)
            //    };

            //    $scope.addBogusInst(abc);
            //}
        }

        $scope.addBogusInst = function (bogusInst) {

            // check for any missing fields
            var missingFields = [];
            var numberErrors = [];
            var hasErrors = false;

            //if (bogusInst.rssdid == null || bogusInst.rssdid == '') {
            //    toastr.error("RSSDID is needed to add an Institution to this scenario.");
            //    return;
            //}

            if (bogusInst.rssdid == null || bogusInst.rssdid === '') {
                missingFields.push("RSSDID");
            }

            if (bogusInst.type == null || bogusInst.type === '') {
                missingFields.push("Type");
            }

            if (bogusInst.branchcount == null || bogusInst.branchcount === '') {
                missingFields.push("Branch Count");
            }

            if (bogusInst.name == null || bogusInst.name === '') {
                missingFields.push("Name");
            }

            if (bogusInst.state == null || bogusInst.state.fipsId == null || !$.isNumeric(bogusInst.state.fipsId)) {
                missingFields.push("State");
            }

            if (bogusInst.city == null || bogusInst.city.name == null || bogusInst.city.name === '') {
                missingFields.push("City");
            }

            if (bogusInst.weight == null || bogusInst.weight === '') {
                missingFields.push("Weight");
            }

            if (bogusInst.deposit == null || bogusInst.deposit === '') {
                missingFields.push("Deposit");
            }

            if (bogusInst.rssdid != null && bogusInst.rssdid !== '' && !$.isNumeric(bogusInst.rssdid)) {
                numberErrors.push("RSSDID must be numeric");
            }

            if (!$.isNumeric(bogusInst.branchcount) || bogusInst.branchcount < 0) {
                numberErrors.push("Branch Count must be >= 0");
            }

            if (!$.isNumeric(bogusInst.weight) || bogusInst.weight < 0) {
                numberErrors.push("Weight must be >= 0");
            }

            if (!$.isNumeric(bogusInst.deposit) || bogusInst.deposit < 0) {
                numberErrors.push("Deposits must be >= 0");
            }

            if (numberErrors.length > 0) {
                hasErrors = true;
                toastr.error(numberErrors.join(',<br /> '), { allowHtml: true });
            }

            if (missingFields.length > 0) {
                hasErrors = true;
                //toastr.error('Missing Fields: <br /> ' + missingFields.join(', '), { allowHtml: true });
                toastr.error('ALL "Additional Institutions:" fields are required.');
            }

            if (hasErrors) {
                return;
            }

            // is rssd part of the real org group
            if ($scope.checkIfInRealMarket(bogusInst.rssdid)) {
                toastr.error('RSSD Id ' + bogusInst.rssdid + ' is already already part of this HHI report.');
                return;
            }


            if (!$scope.model.instBogusRSSDIds) {
                $scope.model.instBogusRSSDIds = [];
                if ($scope.model.instBogus && $scope.model.instBogus.length) {
                    // rebuild rssd list from bogus inst list
                    var numBogusLoaded = $scope.model.instBogus.length;
                    for (var i = 0; i < numBogusLoaded; i++) {
                        var candidateRSSDId = $scope.model.instBogus[i].rssdid;

                        if ($.isNumeric(candidateRSSDId) && $scope.model.instBogusRSSDIds.indexOf(candidateRSSDId) == -1) {
                            $scope.model.instBogusRSSDIds.push(candidateRSSDId); 
                        }
                    }
                }
            }

            if ($scope.model.instBogusRSSDIds.indexOf(bogusInst.rssdid.toString()) != -1 || $scope.model.instBogusRSSDIds.indexOf(Number(bogusInst.rssdid)) != -1) {
                toastr.error("RSSDID has already been added. An RSSDID can only be added once.");
                return;
            }

            $scope.model.instBogus.push(bogusInst);
            $scope.model.instBogusRSSDIds.push(bogusInst.rssdid);
            $scope.resetBogusInst();
            $scope.flagChanges(true);
		}

		$scope.calcBogusCounts = function () {
			var numOthersFound = 0;
			var numCUsFound = 0;
			for (var i = 0; i < $scope.model.instBogus.length; i++) {
				if ($scope.model.instBogus[i].type.toUpperCase() == "CU") {
					++numCUsFound;
				}
			}
			
			$scope.bogusCUCount = numCUsFound;
		}


        // gets the template to ng-include for a table row / item
        $scope.getTargetChildTemplate = function (childorg) {
            return 'displayTarget';
        };

        // gets the template to ng-include for a table row / item
        $scope.getBuyerChildTemplate = function (childorg) {
            return 'displayTarget';
        };



        // gets the template to ng-include for a table row / item
        $scope.getotherChildTemplate = function (childorg) {
            return 'displayTarget';
        };

        $scope.editweighttargetinst = function (childorg) {
            $scope.isEditWeight = true;
            $scope.model.selected = angular.copy(childorg);
            return 'editWeightTarget';
        };

        $scope.editdeposittargetinst = function (childorg) {
            $scope.isEditDeposit = true;
            $scope.model.selected = angular.copy(childorg);
            return 'editDepositTarget';
        };

        $scope.saveweightTargetInst = function (idx) {
            $scope.model.selected.hasChanged = true;
            $scope.model.proFormReportData[idx] = angular.copy($scope.model.selected);
            $scope.reset();
        };

        $scope.saveDepositTargetInst = function (idx) {
            $scope.model.selected.hasChanged = true;
            $scope.model.proFormReportData[idx] = angular.copy($scope.model.selected);
            $scope.reset();
        };

        $scope.anyCustomUpdates = function () {

            if ($scope.model == null)
                return false;

            if ($scope.groupingHasCustomUpdates($scope.TargetOrg))
                return true;
            if ($scope.groupingHasCustomUpdates($scope.BuyerOrg))
                return true;
            if ($scope.groupingHasCustomUpdates($scope.OtherOrg))
                return true;

            if ($scope.model.instBogus.length > 0) {
                return true;
            }

            if ($scope.hasAppliedBogusInsts == true) {
                return true;
            }

            return false;

        };

        $scope.groupingHasCustomUpdates = function (group) {
            return (
                _.filter(group,
                    function (inst) {
                        return inst.hasModfiedHHIWeight ||
                            inst.hasModfiedUnweightedDeposits ||
                            _.filter(inst.childInst,
                                function (org) {
                                    return org.hasModfiedHHIWeight || org.hasModfiedUnweightedDeposits;
                                }).length >
                            0;
                    }).length >
                0);
        };


        $scope.reset = function () {
            $scope.model.selected = {};
            $scope.isEditDeposit = false;
            $scope.isEditWeight = false;
        };

        $scope.switchMarketNumber = function () {
            $scope.showMarketNumbers = true;
            $scope.showMSA = false;
            $scope.showCustomNumbers = false;
        };

        $scope.switchMSA = function () {

            $scope.showMarketNumbers = false;
            $scope.showMSA = true;
            $scope.showCustomNumbers = false;
        };

        $scope.switchCustomMarket = function () {
            $scope.showMarketNumbers = false;
            $scope.showMSA = false;
            $scope.showCustomNumbers = true;
        };

        $scope.showSearchResults = function () {

            $scope.showData = false;
            $scope.instDataReady = false;
            $scope.instLoadData = false;

        };


        $scope.gatherMSA = function () {

            AdvMarketsService
                .gatherMSA()
                .then(function (result) {

                    $scope.msa = result;

                });

        }
        $scope.gatherNONMSA = function () {

            AdvMarketsService
                .gatherNONMSA()
                .then(function (result) {

                    $scope.nonmsa = result;

                });

        }
        // check if an rssdid is part of the real org group
        $scope.checkIfInRealMarket = function (rssdid) {
            var numItems = $scope.hhi.otherOrgProformaItems.length;
            var numChildren = 0;
            for (var i = 0; i < numItems; i++) {
                if (rssdid.toString() == $scope.hhi.otherOrgProformaItems[i].rssdid.toString()) {
                    return true;
                }
                // check child orgs
                numChildren = $scope.hhi.otherOrgProformaItems[i].childInst ? $scope.hhi.otherOrgProformaItems[i].childInst.length : 0;
                for (var j = 0; j < numChildren; j++) {
                    if (rssdid.toString() == $scope.hhi.otherOrgProformaItems[i].childInst[j].rssdid.toString()) {
                        return true;
                    }
                }
            }

            numItems = $scope.hhi.targetProformaItems.length;
            for (var i = 0; i < numItems; i++) {
                if (rssdid.toString() == $scope.hhi.targetProformaItems[i].rssdid.toString()) {
                    return true;
                }
                // check child orgs
                numChildren = $scope.hhi.targetProformaItems[i].childInst ? $scope.hhi.targetProformaItems[i].childInst.length : 0;
                for (var j = 0; j < numChildren; j++) {
                    if (rssdid.toString() == $scope.hhi.targetProformaItems[i].childInst[j].rssdid.toString()) {
                        return true;
                    }
                }
            }

            numItems = $scope.hhi.buyerProformaItems.length;
            for (var i = 0; i < numItems; i++) {
                if (rssdid.toString() == $scope.hhi.buyerProformaItems[i].rssdid.toString()) {
                    return true;
                }
                // check child orgs
                numChildren = $scope.hhi.buyerProformaItems[i].childInst ? $scope.hhi.buyerProformaItems[i].childInst.length : 0;
                for (var j = 0; j < numChildren; j++) {
                    if (rssdid.toString() == $scope.hhi.buyerProformaItems[i].childInst[j].rssdid.toString()) {
                        return true;
                    }
                }
            }

            return false;
        }

        $scope.updateReport = function () {
            //now we send the updated model to the server to reprocess
			$scope.hideDivestAmts();
			$scope.processingData = true;
            AdvMarketsService
                .recalculateProformaHHI($scope.model)
                .then(function (result) {
                    $scope.processReturnData(result);
                    if ($scope.model.instBogus && $scope.model.instBogus.length > 0) {
                        $scope.hasAppliedBogusInsts = true;                        
                    }
                    else {
                        $scope.hasAppliedBogusInsts = false;
                    }
					$scope.flagChanges(false);
					$scope.calcBogusCounts();
                });
        };

        $scope.getInstBranchTotal = function (inst) {

            return $scope.oneLine(inst)
                ? inst.branchCount
                : _.sumBy(inst.childInst, function (e) { return e.branchCount; });

        }

        $scope.clearCustomUpdates = function () {
            //reload the data
			$scope.hideDivestAmts();
			$scope.bogusCUCount = 0;
			processSingleregiontype();			
            $scope.hasAppliedBogusInsts = false;
            $scope.hasNewChanges = false;
        };


        $scope.showProFormaData = function () {
            $scope.showCalProForma = !$scope.showCalProForma;
        }





		$scope.clearCriteria = function () {
			if ($scope.mktPicker.clearAllChecks) { $scope.mktPicker.clearAllChecks(); }
            $scope.criteria.reportType = 'BankandThrift';
            $scope.criteria.regionType = 'bankingMarket';
            $scope.criteria.marketID = '';
            $scope.criteria.msa = null;
            $scope.criteria.nonmsa = null;
            $scope.criteria.state = null;
            $scope.criteria.customMarket = null;
            $scope.criteria.buyerRSSDID = '';

            $scope.criteria.sellerRSSDIDs = [
                {
                    rssdId: '',
                    branchNums: '',
                    branchList: [],
                    checkModel: []
                }
			];

			$scope.resetBogusInst();

			// clear out the buyer/survivor
			$scope.foundSurvivor = null;

			// clear out any custom updates that have been made
			$scope.bogusCUCount = 0;
			$scope.hasAppliedBogusInsts = false;
			$scope.hasNewChanges = false;

            //default to activation of the screen
            $scope.showData = false;
            $scope.processingData = false;
        };

        $scope.criteriaEntered = function () {
            return $scope.criteria.reportType != 'BankandThrift' ||
                $scope.criteria.regionType != 'bankingMarket' ||
                $scope.criteria.marketID != '' ||
                $scope.criteria.msa != null ||
                $scope.criteria.state != null ||
                $scope.criteria.customMarket != null ||
                $scope.criteria.buyerRSSDID != '' ||
                $scope.sellersAnyEntered();
        };

        $scope.formReady = function () {
            return $scope.criteria.buyerRSSDID != '' &&
                $scope.sellersAllEntered() &&
                ($scope.criteria.market != '' ||
                    $scope.criteria.msa != null ||
                    $scope.criteria.state != null ||
                    $scope.criteria.customMarket != null
                );
        };

        $scope.getTotalBranches = function () {

            if ($scope.showPostMerger) {

                var mainTotal = _.sumBy($scope.ResultOrg, function (e) { return $scope.getInstBranchTotal(e); }) +
                    _.sumBy($scope.OtherOrg, function (e) { return $scope.getInstBranchTotal(e); });

                _.each($scope.TargetOrg, function (inst) {
                    if (inst.branches && inst.branches.length > 0)
                        mainTotal += inst.branchCount - inst.branches.length;
                });

                return mainTotal;
            }

            return _.sumBy($scope.OtherOrg, function (e) { return $scope.getInstBranchTotal(e); });
        };

        $scope.sellersAllEntered = function () {
            return (_.find($scope.criteria.sellerRSSDIDs, function (e) { return (e.rssdId == null || e.rssdId == '') })) == null;

        };

        $scope.sellersAnyEntered = function () {
            return (_.find($scope.criteria.sellerRSSDIDs, function (e) { return !(e.rssdId == null || e.rssdId == '') }) != null);
        };

        $scope.isSellerRSSDID = function (rssd) {
            return _.find($scope.criteria.sellerRSSDIDs, function (e) { return Number(e.rssdId) == Number(rssd); }) != null;
        };

        $scope.isSBuyerRSSDID = function (rssd) {
            return $scope.criteria.buyerRSSDID == rssd;
        };

        $scope.addSeller = function () {
            $scope.criteria.sellerRSSDIDs.push({
                rssdId: '',
                branchNums: '',
                branchList: [],
                checkModel: []
            });
        };

        $scope.deleteSeller = function (index) {
            $scope.criteria.sellerRSSDIDs.splice(index, 1);

            if ($scope.criteria.sellerRSSDIDs.length == 0) {
                $scope.criteria.sellerRSSDIDs = [
                    {
                        rssdId: '',
                        branchNums: '',
                        branchList: [],
                        checkModel: []
                    }
                ];
            }
        }

        $scope.generateExcel = function () {




            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/report/HHIDepositAnalysisExcelExport', true);
            xhr.responseType = 'blob';
            xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
            xhr.onload = function (e) {

                if (this.status == 200) {
                    var blob = new Blob([this.response], { type: 'application/vnd.ms-excel' });
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        window.navigator.msSaveOrOpenBlob(blob, "HHIDepositAnalysisProforma.xlsx");
                    }
                    else {
                        var downloadUrl = URL.createObjectURL(blob);
                        var a = document.createElement("a");
                        a.href = downloadUrl;
                        a.download = "HHIDepositAnalysisProforma.xlsx";
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    alert('Unable to download excel.');
                }
			};

			if ($scope.thriftWeightRuleTypeId && !isNaN($scope.thriftWeightRuleTypeId) && (!$scope.model.thriftWeightRuleId || isNaN($scope.model.thriftWeightRuleId))) {
				$scope.model.thriftWeightRuleId = $scope.thriftWeightRuleTypeId;	// if missing, add in the thrift weight rule id
			}

            xhr.send(JSON.stringify($scope.model));


        };

        $scope.hasMultipleMarkets = function () {
            return !$.isNumeric($scope.criteria.marketID) && $scope.criteria.marketID.indexOf(',') > 0;
        };

        $scope.processProformaReport = function () {

            if ($scope.criteria.regionType == 'bankingMarket') {

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/report/HHIDepositAnalysispdfExport', true);
                xhr.responseType = 'blob';
                xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
                xhr.onload = function (e) {
                    if (this.status == 200) {
                        var blob = new Blob([this.response], { type: 'application/pdf' });
                        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                            window.navigator.msSaveOrOpenBlob(blob, "HHIDepositAnalysisProforma.pdf");
                        }
                        else {
                            var downloadUrl = URL.createObjectURL(blob);
                            var a = document.createElement("a");
                            a.href = downloadUrl;
                            a.download = "HHIDepositAnalysisProforma.pdf";
                            document.body.appendChild(a);
                            a.click();
                            toastr.success("Report generated and downloaded.");
                        }

                    } else {
                        toastr.error('Unable to download pdf.');
                    }
				};
				if ($scope.thriftWeightRuleTypeId && !isNaN($scope.thriftWeightRuleTypeId) && (!$scope.model.thriftWeightRuleId || isNaN($scope.model.thriftWeightRuleId))) {
					$scope.model.thriftWeightRuleId = $scope.thriftWeightRuleTypeId;	// if missing, add in the thrift weight rule id
				}
                xhr.send(JSON.stringify($scope.model));


            }
            else if ($scope.criteria.regionType == 'state') {
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/report/HHIDepositAnalysispdfState', true);
                xhr.responseType = 'blob';
                xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
                xhr.onload = function (e) {
                    if (this.status == 200) {
                        var blob = new Blob([this.response], { type: 'application/pdf' });
                        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                            window.navigator.msSaveOrOpenBlob(blob, "HHIDepositAnalysisProforma.pdf");
                        }
                        else {
                            var downloadUrl = URL.createObjectURL(blob);
                            var a = document.createElement("a");
                            a.href = downloadUrl;
                            a.download = "HHIDepositAnalysisProforma.pdf";
                            document.body.appendChild(a);
                            a.click();
                            toastr.success("Report generated and downloaded.");
                        }
                    } else {
                        toastr.error('Unable to download pdf.');
                    }
                };
                xhr.send(JSON.stringify($scope.model));

            }
            else if ($scope.criteria.regionType == 'msa') {

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/report/MsaHHIDepositAnalysispdfExport', true);
                xhr.responseType = 'blob';
                xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
                xhr.onload = function (e) {
                    if (this.status == 200) {
                        var blob = new Blob([this.response], { type: 'application/pdf' });
                        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                            window.navigator.msSaveOrOpenBlob(blob, "HHIDepositAnalysisProforma.pdf");
                        }
                        else {
                            var downloadUrl = URL.createObjectURL(blob);
                            var a = document.createElement("a");
                            a.href = downloadUrl;
                            a.download = "HHIDepositAnalysisProforma.pdf";
                            document.body.appendChild(a);
                            a.click();
                            toastr.success("Report generated and downloaded.");
                        }
                    } else {
                        toastr.error('Unable to download pdf.');
                    }
                };
                xhr.send(JSON.stringify($scope.model));


                //if ($scope.criteria.buyerRSSDID != '') {
                //    var targetRSSDID = '';
                //    for (var i = 0; i < $scope.criteria.sellerRSSDIDs.length; i++) {
                //        if (i > 0) {
                //            targetRSSDID = targetRSSDID + ',' + $scope.criteria.sellerRSSDIDs[i].rssdId;
                //        }
                //        else {
                //            targetRSSDID = $scope.criteria.sellerRSSDIDs[i].rssdId;
                //        }
                //    }
                //    $window.open('/report/CommonmsaCustomMarketHHIProformaPDF?hhivalue=' + $scope.criteria.msa.msaId + '&regiontype=msa&buyer=' + $scope.criteria.buyerRSSDID + '&target=' + targetRSSDID, 'target');
                //}
                //else {
                //    $window.open('/report/MarketHhiPDFFormsacustommarket?hhivalue=' + $scope.criteria.msa.msaId + '&regiontype=msa', 'target');
                //}
            }
            else if ($scope.criteria.regionType == 'customMarket') {
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/report/CustomMarketHHIDepositAnalysispdfExport', true);
                xhr.responseType = 'blob';
                xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
                xhr.onload = function (e) {
                    if (this.status == 200) {
                        var blob = new Blob([this.response], { type: 'application/pdf' });
                        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                            window.navigator.msSaveOrOpenBlob(blob, "HHIDepositAnalysisProforma.pdf");
                        }
                        else {
                            var downloadUrl = URL.createObjectURL(blob);
                            var a = document.createElement("a");
                            a.href = downloadUrl;
                            a.download = "HHIDepositAnalysisProforma.pdf";
                            document.body.appendChild(a);
                            a.click();
                            toastr.success("Report generated and downloaded.");
                        }
                    } else {
                        toastr.error('Unable to download pdf.');
                    }
                };
                xhr.send(JSON.stringify($scope.model));
                //if ($scope.criteria.buyerRSSDID != '') {
                //    //we need to see if there are more than 1 target if so build a string and pass it on
                //    var targetRSSDID = '';
                //    for (var i = 0; i < $scope.criteria.sellerRSSDIDs.length; i++) {
                //        if (i > 0)
                //        {
                //            targetRSSDID = targetRSSDID + ',' + $scope.criteria.sellerRSSDIDs[i].rssdId;
                //        }
                //        else
                //        {
                //            targetRSSDID = $scope.criteria.sellerRSSDIDs[i].rssdId;
                //        }
                //    }

                //    $window.open('/report/CommonmsaCustomMarketHHIProformaPDF?hhivalue=' + $scope.criteria.customMarket.customMarketId + '&regiontype=custommarket&buyer=' + $scope.criteria.buyerRSSDID + '&target=' + targetRSSDID, 'target');
                //}
                //else {
                //    $window.open('/report/MarketHhiPDFFormsacustommarket?hhivalue=' + $scope.criteria.customMarket.customMarketId + '&regiontype=custommarket', 'target');
                //}

            }


        };


        $scope.UpdateCountysAndCitys = function () {

            $scope.newBogusInst.city = null;

            var data = {
                stateFIPSId: $scope.newBogusInst.state.fipsId
            };

            StatesService.getCityNames(data).then(function (result) {
                $scope.bogusCities = result;
            });

        }

        function activate() {

			$scope.clearCriteria();
			$scope.bogusCUCount = 0;

            // get dates for footer display
            AdvMarketsService.checkIfUsingArchive().then(function (result) {
                $scope.isArchiveData = result;
            });
            AdvMarketsService.getLastArchiveHistoryDate().then(function (result) {
                $scope.lastStructChangeDate = result;
            });


            //need to come back and have it load only when we need to but if it is loaded then dont reload
            AdvMarketsService.GetCustomMarkets().then(function (result) {
                $scope.customMarkets = result;
            });


            //need to come back and have it load only when we need to but if it is loaded then dont reload
            AdvMarketsService
                .gatherMSA()
                .then(function (result) {
                    $scope.msa = result;
                });

            AdvMarketsService
                .gatherNONMSA()
                .then(function (result) {
                    $scope.nonmsa = result;
                });

            var data = {
                includeDC: true,
                includeTerritories: true
            };

            StatesService.getStateSummaries(data).then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

            if ($stateParams.marketId) {
                $scope.criteria.regionType = 'bankingMarket';
                $scope.criteria.marketID = $stateParams.marketId;
                $scope.gatherHHIDeposits();

                loadOverOneBillionInfo();
            }

            $scope.activationComplete = true;

        }

        activate();

        function loadOverOneBillionInfo() {
            $scope.numBranchesOverDepositCap = 0;
            $scope.instRssdOverDepositCap = [];

            var data = {
                depositAmt: '1000.0',
                marketId: $scope.criteria.marketID
            };

            AdvMarketsService.getNumBranchesOverDepositAmt(data)
                .then(function (result) {
                    $scope.numBranchesOverDepositCap = result;
                });

            AdvMarketsService.getRssdsWithBranchesOverDepositAmt(data)
                .then(function (result) {
                    $scope.instRssdOverDepositCap = result;
                });
        }

        //this is simple flow first, need switch this from an if and combine logic
        function handleHHIDepositAnalysis() {
            $scope.numBranchesOverDepositCap = 0;
            $scope.instRssdOverDepositCap = [];

			if ($scope.hideDivestAmts) { $scope.hideDivestAmts(); }

			$scope.chcheckForThriftBankCombo = true;

            if ($scope.criteria.regionType == null) {
                $scope.processingData = false;
                toastr.error("You are required to enter a region type!");
                return;
            }

            if ($scope.criteria.reportType == null) {
                $scope.processingData = false;
                toastr.error("You are required to enter a report type!");
                return;
            }


            if (($scope.criteria.buyerRSSDID == null || $scope.criteria.buyerRSSDID == '') && $scope.sellersAnyEntered()) {
                toastr.error("You are required to enter a Survivor if you have entered any Non-Survivors!");
                return;
            }

            if ($scope.criteria.buyerRSSDID != null && $scope.criteria.buyerRSSDID != '' && !$scope.sellersAnyEntered()) {
                toastr.error("You are required to enter at least one Non-Survivor if you have entered a Survivor!");
                return;
            }

            if ($scope.criteria.buyerRSSDID != null && $scope.criteria.buyerRSSDID != '' && !$scope.sellersAllEntered()) {
                toastr.error("Any added Non-Survivors cannot have a blank RSSD ID.  Please provide the RSSD ID for all added Non-Survivors.");
                return;
            }


            if ($scope.criteria.regionType == 'bankingMarket') {
                if ($scope.criteria.marketID == null || $scope.criteria.marketID == '') {

                    toastr.error("You are required to enter a Market Number!");
                    return;
                }
                //check mutiple market or single one
                if (!$.isNumeric($scope.criteria.marketID) && $scope.criteria.marketID.indexOf(',') > 0) {
                    processMutipleregiontype();
                }
                else {
                    loadOverOneBillionInfo();
                    processSingleregiontype();
                }
            }
            else if ($scope.criteria.regionType == 'msa') {
                if ($scope.criteria.msa == null) {

                    toastr.error("You are required to enter a MSA!");
                    return;
                }
                //we can only have 1 msa  
                processSingleregiontype();
            }
            else if ($scope.criteria.regionType == 'nonmsa') {
                if ($scope.criteria.nonmsa == null) {

                    toastr.error("You are required to enter a NonMSA!");
                    return;
                }
                //we can only have 1 msa  
                processSingleregiontype();
            }
            else if ($scope.criteria.regionType == 'state') {
                if ($scope.criteria.state == null) {

                    toastr.error("You are required to enter a State!");
                    return;
                }

                StatesService.getStateCapPercent($scope.criteria.state)
                .then(function (result) {
                    if (result && !isNaN(result)) {
                        $scope.stateDepositCapPercent = result;
                    }                       
                });                    

                var targetRSSDID = '';
                for (var i = 0; i < $scope.criteria.sellerRSSDIDs.length; i++) {
                    if (i > 0) {
                        targetRSSDID = targetRSSDID + ',' + $scope.criteria.sellerRSSDIDs[i].rssdId;
                    }
                    else {
                        targetRSSDID = $scope.criteria.sellerRSSDIDs[i].rssdId;
                    }
                }

                //var brids = getBranchIds($scope.criteria.sellerRSSDIDs).join(",")
                //AdvMarketsService.getAllCommonStates($scope.criteria.buyerRSSDID, targetRSSDID, brids)
                //.then(function (result) {
                //    $scope.overlappingStatesLabel = '';
                //    if (result) {
                //        for (var i = 0; i < result.length; i++) {
                //            if (i > 0) { $scope.overlappingStatesLabel += ', '; }
                //            $scope.overlappingStatesLabel += result[i].postalCode;
                //        }                        
                //    }
                //});

                //we can only have 1 msa
                processSingleregiontype();
            }
            else if ($scope.criteria.regionType == 'customMarket') {
                if ($scope.criteria.customMarket == null) {

                    toastr.error("You are required to enter a Custom Market Number!");
                    return;
                }
                //we can only have 1 msa
                processSingleregiontype();
            }

        }



        function getBranchIds(sellers) {

            var result = [];

            _.each(sellers,
                function (seller) {
                    if (seller.branchNums != '') {
                        var nums = seller.branchNums.split(',');
                        _.each(nums,
                            function (num) {
                                var branch = _.find(seller.branchList, { facility: Number(num.trim()) });
                                if (branch) {
                                    result.push(branch.branchId);
                                }
                            });
                    }
                });

            return result;

        }


        function moveBranches(insts) {
            _.each(insts,
                function (inst) {

                    var branches = [];

                    _.each(inst.childInst,
                        function (org) {

                            _.each(org.branches, function (branch) {
                                branches.push({
                                    rssdid: branch.branchNum,
                                    entityName: branch.name,
                                    entityType: 'Branch',
                                    branchCount: 0,
                                    city: branch.cityName,
                                    state: branch.statePostalCode,
                                    preMergerUnWeightedDeposits: branch.totalDeposits,
                                    postMergerUnWeightedDeposits: branch.totalDeposits
                                });
                            });

                        });


                    if (inst.childInst)
                        inst.childInst = inst.childInst.concat(branches);
                    else if (inst.branches) {
                        var branches = [];
                        _.each(inst.branches, function (branch) {
                            branches.push({
                                rssdid: branch.branchNum,
                                entityName: branch.name,
                                entityType: 'Branch',
                                branchCount: 0,
                                city: branch.cityName,
                                state: branch.statePostalCode,
                                preMergerUnWeightedDeposits: branch.totalDeposits,
                                postMergerUnWeightedDeposits: branch.totalDeposits
                            });
                        });

                        inst.childInst = branches;
                    }
                });
        }

        $scope.isBogusInst = function (inst) {
            return $scope.model != null && $scope.model.instBogus != null ? _.filter($scope.model.instBogus, function (e) { return e.rssdid == inst.rssdid }).length > 0 : false;
        };
        $scope.getBankType = function (otherOrg) {            

            if (otherOrg.entitySubClassification == 5) {
                return 'BANK';
            }
            else if (otherOrg.entitySubClassification == 6 && otherOrg.weight == 1) {
                return 'CSA THRIFT';
            }
            else {
                return 'THRIFT';
            }
        };

        $scope.processReturnData = function (data) {

            $scope.errorList = [];
            $scope.resetBogusInst();

            moveBranches(data.proFormReportData.targetProformaItems);
            moveBranches(data.proFormReportData.resultingOrgProformaItems);

            //populate the org list
            $scope.TargetOrg = data.proFormReportData.targetProformaItems;
            $scope.BuyerOrg = data.proFormReportData.buyerProformaItems;
            $scope.ResultOrg = _.filter(data.proFormReportData.resultingOrgProformaItems, function (e) {
                return e.rssdid == $scope.criteria.buyerRSSDID || _.filter(e.childInst, function (c) { 
                    return c.rssdid == $scope.criteria.buyerRSSDID }).length > 0
            });
            $scope.OtherOrg = data.proFormReportData.otherOrgProformaItems;


            // confirm Buyer acquired if requested
            if ($scope.criteria.buyerRSSDID != null && $scope.criteria.buyerRSSDID != '' && ($scope.BuyerOrg == null || $scope.BuyerOrg.length == 0)) {
                $scope.errorList.push('Survivor, RSSDID ' +
                    $scope.criteria.buyerRSSDID +
                    ', does not have a presence in market ' +
                    $scope.criteria.marketID +
                    '.');
            }

            // confirm all Targets acquired if requested
            if ($scope.sellersAnyEntered()) {

                var targets = _.map($scope.criteria.sellerRSSDIDs, 'rssdId');
                var returnedTargets = _.map(_.flatMap($scope.TargetOrg, function (e) { return [e].concat(e.childInst); }), 'rssdid');
                var missingTargets = _.filter(targets, function (e) { return _.indexOf(returnedTargets, Number(e)) == -1; });

                if (missingTargets.length > 0) {
                    $scope.errorList = $scope.errorList.concat(_.map(missingTargets,
                        function (e) {
                            return 'Non-survivor, RSSDID ' +
                                e +
                                ', does not have a presence in market ' +
                                $scope.criteria.marketID +
                                '.';
                        }));

                }

            }

            $scope.showPostMerger = $scope.TargetOrg.length > 0 &&
                $scope.BuyerOrg.length > 0 &&
                $scope.ResultOrg.length > 0;

            if ($scope.errorList.length > 0) {
                _.each($scope.errorList, function (e) { toastr.error(e); });
                $scope.showData = false;
                $scope.processingData = false;
                $scope.hhiDataReady = false;
                $scope.hhi = null;
                $scope.model = null;
            } else {

                $scope.hhi = data.proFormReportData;
                $scope.hhiOrig = data.proFormReportData;
				$scope.model = data;
				$scope.model.thriftWeightRuleTypeId = $scope.thriftWeightRuleTypeId;
				$scope.model.reportTypeTitle = $scope.cbtMessage;
                $scope.model.selected = {};

                if ($scope.model.instBogus == null) {
                    $scope.model.instBogus = [];
                    $scope.model.instBogusRSSDIds = [];
                }

                $scope.hhiDataReady = true;

                $scope.exceedsAuthority = data.proFormReportData.exceedsAuthority;

                $scope.runDate = new Date();
                $scope.showData = true;
                $scope.processingData = false;
                $('body,html').animate({ scrollTop: $scope.hideCriteria ? 200 : 550 }, 500);

            }

        }


        function processSingleregiontype(treatTHCBuyerAsBHC, blockThriftBankComboDialog) {
            $scope.creditUnionCount = 0;

            $scope.processingData = true;

			if ($scope.criteria.reportType == 'BankandThrift') {
				$scope.cbtMessage = '(For Commercial Bank and Thrift Organizations)';
				$scope.thriftWeightRuleTypeId = THRIFT_WEIGHT_RULE_IDS.Default;
			}
			else if ($scope.criteria.reportType == 'BOGBankandThrift') {
				$scope.cbtMessage = '(For Commercial Bank and Thrift Organizations - BOG Weight Rules)';
				// temp patch for case where there are no thrifts. 
				if (!$scope.hhi || $scope.hhi.numThriftsPre > 0) {
					$scope.thriftWeightRuleTypeId = THRIFT_WEIGHT_RULE_IDS.BOG;
				}
				else {
					$scope.thriftWeightRuleTypeId = THRIFT_WEIGHT_RULE_IDS.Default;
				}
			}
			else if ($scope.criteria.reportType == 'DOJBankandThrift') {
				$scope.cbtMessage = '(For Commercial Bank and Thrift Organizations - DOJ Weight Rules)';
				// temp patch for case where there are no thrifts. 
				if (!$scope.hhi || $scope.hhi.numThriftsPre > 0) {
					$scope.thriftWeightRuleTypeId = THRIFT_WEIGHT_RULE_IDS.DOJ;
				}
				else {
					$scope.thriftWeightRuleTypeId = THRIFT_WEIGHT_RULE_IDS.Default;
				}
			}
			else {
				$scope.cbtMessage = '(For Commercial Bank Organizations Only)';
				$scope.thriftWeightRuleTypeId = THRIFT_WEIGHT_RULE_IDS.Default;
			}

            // Details for the report header
            $scope.reportDetails = {
                market: null, // acquire asynchronously below...
                state: $scope.criteria.state,
                msa: $scope.criteria.msa,
                nonmasa: $scope.criteria.nonmsa,
				customMarket: $scope.criteria.customMarket
			}	

			// get any needed special thrift weight handling footnote info	
			AdvMarketsService.getThriftWeightFootnote($scope.thriftWeightRuleTypeId)
				.then(function (result) {
					if (result && result.length && result.length > 0) {
						$scope.thriftWeightRuleFootnote = result;
					}
					else {
						$scope.thriftWeightRuleFootnote = '';
					}
			});


            // Get market info if needed.
			if ($scope.criteria.marketID != null && $scope.criteria.marketID != '') {
				AdvMarketsService.getPendingCount($scope.criteria.marketID)
					.then(function (result) {
						$scope.pendingTransCount = result;
						$scope.reportDetails.pendingTransCount = result;

						AdvMarketsService.getMarketByIdAdv({ marketId: $scope.criteria.marketID, getDefinition: true })
							.then(function (result) {
								$scope.reportDetails.market = result.definition;
							});		
					});               		
            }

            // request dataset
            var data = {
                marketID: $scope.criteria.marketID,
                msaID: $scope.criteria.msa == null ? null : $scope.criteria.msa.msaId,
                nonmsaID: $scope.criteria.nonmsa == null ? null : $scope.criteria.nonmsa.nonMSAId,
                stateId: $scope.criteria.state == null ? null : $scope.criteria.state.fipsId,
                custommarkets: $scope.criteria
                    .customMarket ==
                    null
                    ? null
                    : $scope.criteria.customMarket.customMarketId,
                blnbankandthrift: $scope.criteria.reportType.includes('BankandThrift'),
                buyer: $scope.criteria.buyerRSSDID,
                targets: _.map(_.filter($scope.criteria.sellerRSSDIDs,
                    function (e) { return e.rssdId != null && e.rssdId != ''; }),
                    'rssdId').join(","),
                branches: getBranchIds($scope.criteria.sellerRSSDIDs).join(","),
				treatTHCBuyerAsBHC: treatTHCBuyerAsBHC,
				weightRuleTypeId: $scope.thriftWeightRuleTypeId
            };

            if (data.custommarkets) {
                AdvMarketsService.GetCustomMarketContentsLabel(data.custommarkets)
                    .then(function (result) {
                        if (!$scope.reportDetails.market) { $scope.reportDetails.market = []; }
                        $scope.reportDetails.market.description = result;
                    });
            }

            AdvMarketsService.validateProformaHHI(data).then(function (result) {

                if (result.length > 0) {

                    $scope.showData = false;
                    $scope.processingData = false;
                    $scope.hhiDataReady = false;
                    $scope.hhi = null;
                    $scope.model = null;

                    _.each(result,
                        function (e) {



                            toastr.error(e);
                        });


                } else {

                    // Make request
                    AdvMarketsService
                        .getProformaHHI(data)
                        .then(function (result) {
                            if (result.needsTHCBuyerTreatmentInfo && !blockThriftBankComboDialog) {
                                $uibModal.open({
                                    animation: true,
                                    modal: true,
                                    backdrop: false,
                                    size: 'lg',
                                    templateUrl: 'AppJs/advanced/markets/views/analysis/_slhc.html',
                                    controller: [
                                        '$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
                                            $scope.select = function (value) {
                                                $uibModalInstance.close(value);
                                            };
                                            $scope.cancel = function () {
                                                $uibModalInstance.close('cancel');
                                            };
                                        }
                                    ]
                                }).result.then(function (result) {

                                    $scope.bhcOrthc = result;
                                    if ($scope.bhcOrthc == "cancel") {
                                        return;
                                    }
                                    if ($scope.bhcOrthc == "SLHC") {
                                        processSingleregiontype(false, true);
                                    } else
                                        processSingleregiontype(true, true);
                                });
                            } else {
                                if (result.validationMessage && result.validationMessage.length > 0) { toastr.error(result.validationMessage); }
                            }

                            if (result.validationMessage || (result.needsTHCBuyerTreatmentInfo && !blockThriftBankComboDialog)) {

                                $scope.showData = false;
                                $scope.processingData = false;
                                $scope.hhiDataReady = false;
                                $scope.hhi = null;
                                $scope.model = null;

                                //if (result.validationMessage.startsWith("An SLHC is purchasing a bank.")) {                               

                            } else {
                                $scope.processReturnData(result);
                            }

                            // check if credit union button needs enabled
                            AdvMarketsService.getCreditUnionCountForHHI(data).then(function (result) {
                                $scope.creditUnionCount = result;
                            });

                            // check if we need to display the credit union purchased bank/thrift notice.
                            AdvMarketsService.hasCUNonCUPurchase($scope.criteria.marketID).then(function (result) {
                                $scope.showCUPurchasedBankNote = result;
                            });

                        });
                }
            });

        }


        function processMutipleregiontype() {


            var data = {
                reportType: $scope.criteria.reportType,
                regionType: $scope.criteria.regionType,
                multipleMarkets: $scope.criteria.marketID,
                blnbankandthrift: $scope.criteria.reportType == 'BankandThrift',
                buyer: $scope.criteria.buyerRSSDID,
                branches: getBranchIds($scope.criteria.sellerRSSDIDs).join(","),
                targets: _.map(_.filter($scope.criteria.sellerRSSDIDs,
                    function (e) {
                        return e.rssdId != null && e.rssdId != '' && e.branchNums == '';
                    }),
                    'rssdId').join(",")
            };


            $scope.processingData = true;


            AdvMarketsService.validateProformaHHI(data).then(function (result) {

                if (result.length > 0) {

                    $scope.showData = false;
                    $scope.processingData = false;
                    $scope.hhiDataReady = false;
                    $scope.hhi = null;
                    $scope.model = null;

                    _.each(result,
                        function (e) {


                            toastr.error(e);
                        });
                    $scope.processingData = false;


                } else {

                    data = {
                        reportType: $scope.criteria.reportType,
                        regionType: $scope.criteria.regionType,
                        marketNumbers: $scope.criteria.marketID,
                            branches: getBranchIds($scope.criteria.sellerRSSDIDs).join(","),
                        msa: $scope.criteria.msa,
                        stateId: $scope.criteria.state == null ? null : $scope.criteria.state.fipsId,
                        customMarket: $scope.criteria.customMarket,
                        buyerRSSDID: $scope.criteria.buyerRSSDID,
                        sellerRSSDID: _.map(_.filter($scope.criteria.sellerRSSDIDs, function (seller) { return seller.branchNums == "" }), 'rssdId').join(",")
                    };
                    //so we need to generate the pdf forms for the markets
                    //if we are using the marketnumber then 
                    if (data.regionType == 'bankingMarket') {
                        if (!$scope.criteria.buyerRSSDID) {
                            $window.open('/report/markethhipdfformutiplemarkets?marketId=' + $scope.criteria.marketID, 'target');
                        }
                        else {
                            $window.open('/report/CommonMarketProFormaPDF?markets=' + data.marketNumbers + '&buyer=' + data.buyerRSSDID + '&target=' + data.sellerRSSDID + '&branches=' + data.branches, 'target');
                        }

                        toastr.success("Report generated and ran in a new window.");
                    }
                    else if (data.regionType == 'msa') {
                        if (!$scope.criteria.buyerRSSDID) {
                            var targetRSSDID = '';
                            for (var i = 0; i < $scope.criteria.sellerRSSDIDs.length; i++) {
                                if (i > 0) {
                                    targetRSSDID = targetRSSDID + ',' + $scope.criteria.sellerRSSDIDs[i].rssdId;
                                }
                                else {
                                    targetRSSDID = $scope.criteria.sellerRSSDIDs[i].rssdId;
                                }
                            }
                            $window.open('/report/CommonmsaCustomMarketHHIProformaPDF?hhivalue=' + $scope.criteria.msa.msaId + '&regiontype=msa&buyer=' + $scope.criteria.buyerRSSDID + '&target=' + targetRSSDID, 'target');
                        }
                        else {
                            $window.open('/report/MarketHhiPDFFormsacustommarket?hhivalue=' + $scope.criteria.msa.msaId + '&regiontype=msa', 'target');
                        }
                    }
                    else if (data.regionType == 'customMarket') {
                        if (!$scope.criteria.buyerRSSDID) {
                            var targetRSSDID = '';
                            for (var i = 0; i < $scope.criteria.sellerRSSDIDs.length; i++) {
                                if (i > 0) {
                                    targetRSSDID = targetRSSDID + ',' + $scope.criteria.sellerRSSDIDs[i].rssdId;
                                }
                                else {
                                    targetRSSDID = $scope.criteria.sellerRSSDIDs[i].rssdId;
                                }
                            }
                            $window.open('/report/CommonmsaCustomMarketHHIProformaPDF?hhivalue=' + $scope.criteria.customMarket.customMarketId + '&regiontype=custommarket&buyer=' + $scope.criteria.buyerRSSDID + '&target=' + targetRSSDID, 'target');
                        }
                        else {
                            $window.open('/report/MarketHhiPDFFormsacustommarket?hhivalue=' + $scope.criteria.customMarket.customMarketId + '&regiontype=custommarket', 'target');
                        }

                    }


                }

                $scope.processingData = false;
            });


        }

        $scope.beginEditingWeight = function (inst) {
            inst.editingWeight = true;
            inst.origWeight = inst.weight.toString();
            inst.weightModifiedOriginally = inst.hasModfiedHHIWeight ? "Y" : "N";
        }

        $scope.resetWeight = function (inst) {
            inst.editingWeight = false;
            inst.weight = Number(inst.origWeight);
            inst.hasModfiedHHIWeight = inst.weightModifiedOriginally == "Y";
        }


        $scope.beginEditingDeposit = function (inst) {
            inst.editingDeposits = true;
            inst.origDeposit = inst.preMergerUnWeightedDeposits.toString();
            inst.depositsModifiedOriginally = inst.hasModfiedUnweightedDeposits ? "Y" : "N";
        }

        $scope.resetDeposit = function (inst) {
            inst.editingDeposits = false;
            inst.preMergerUnWeightedDeposits = Number(inst.origDeposit);
            inst.hasModfiedUnweightedDeposits = inst.depositsModifiedOriginally == "Y";
        }

        $scope.lookupAttestment = function (institution, rssdId) {

            if (rssdId.length < 5) {
                $scope.foundSurvivor = null;
                return;
            }

            AdvInstitutionsService
                .getNonHHIInstitutionsSearchData({ rssd: rssdId })
                .then(function (result) {

                    $scope.foundSurvivor = null;

                    if (angular.isArray(result) && result.length == 1) {

                        var root = result[0];
              
                        if (root.rssdId == Number(rssdId)) {
                            $scope.foundSurvivor = root;
                        } else {
                            var org = _.find(root.orgs, { 'rssdId': Number(rssdId) });
                            if (org)
                                $scope.foundSurvivor = org;
                        }
                    }

                });

        };


        $scope.lookupAttestmentNonSurvivor = function (seller, rssdId) {

            if (!seller) return;

            if (rssdId.length < 5) {
                seller.foundNonSurvivor = null;
                return;
            }

            AdvInstitutionsService
                .getNonHHIInstitutionsSearchData({ rssd: rssdId })
                .then(function (result) {

                    seller.foundNonSurvivor = null;

                    if (angular.isArray(result) && result.length == 1) {

                        var root = result[0];

                        if (root.rssdId == Number(rssdId)) {
                            seller.foundNonSurvivor = root;
                        } else {
                            var org = _.find(root.orgs, { 'rssdId': Number(rssdId) });
							if (org) {
								seller.foundNonSurvivor = org;
								seller.branchNums = [];
							}
                        }
                    }

                });

		};

		$scope.hideDivestAmts = function () {
			$scope.showDivestCalcResults = false;
		}

		$scope.toggleShowDivestData = function () {
			$scope.showDivestCalcResults = !$scope.showDivestCalcResults; // toggle the show/no show of results
		}

		$scope.calcDivestAmounts = function(isDivestingToThrift) {
			if (isNaN($scope.criteria.marketID) || isNaN($scope.criteria.buyerRSSDID) || !$scope.criteria.sellerRSSDIDs || $scope.criteria.sellerRSSDIDs.length == 0) {
				return;   // we don't have the necessary data to do calculation
			}

			if ($scope.anyCustomUpdates()) {
				return;  // dont allowed with custom updates
			}

			$scope.toggleShowDivestData();	

			if (!$scope.showDivestCalcResults) {
				return; // we closed the results, no need to calculate
			}

			// calc divesting to incoming bank
			$scope.divestBankWorking = true;
			$scope.calcDivestToOrgType(0);

			// calc divesting to incoming thrift
			$scope.divestThriftWorking = true;
			$scope.calcDivestToOrgType(1);
		}

		$scope.calcDivestToOrgType = function (orgTypeId) {
			if (isNaN($scope.criteria.marketID) || isNaN($scope.criteria.buyerRSSDID) || !$scope.criteria.sellerRSSDIDs || $scope.criteria.sellerRSSDIDs.length == 0) {
				return;   // we don't have the necessary data to do calculation
			}

			// get org type to which we are divesting (bank or thrift)
			var isDivestingToThrift = false;

			if (orgTypeId == 1) {
				isDivestingToThrift = true;				
			}

			// get data for calculation	
			// target branch ids
			var targetBranchIds = [];

			// get target institution rssdIds
			targetBranchIds = getBranchIds($scope.criteria.sellerRSSDIDs);
			var targetRssdIds = [];
			for (var i = 0; i < $scope.criteria.sellerRSSDIDs.length; i++) {
				targetRssdIds.push(Number($scope.criteria.sellerRSSDIDs[i].rssdId));
			}	

			var divToOrgTypeId = isDivestingToThrift ? 1 : 0;

			var banksOnlyInHHI = ($scope.criteria.reportType && !$scope.criteria.reportType.toUpperCase().includes('THRIFT'));

			AdvMarketsService
				.getDivestAmount(Number($scope.criteria.marketID), Number($scope.criteria.buyerRSSDID), targetBranchIds, targetRssdIds, divToOrgTypeId, banksOnlyInHHI)
				.then(function (result) {
					if (isDivestingToThrift) {
						$scope.divestToThrift = result;
						$scope.divestThriftWorking = false;
					}
					else {
						$scope.divestToBank = result;
						$scope.divestBankWorking = false;
					}
				});
		}


        function getHhiPageCount() {
            return Math.ceil($scope.hhiData.length / $scope.hhiItemsPerPage);
        }

        function setPages() {
            $scope.hhiDataPages = _.chunk($scope.hhiData, $scope.hhiItemsPerPage);
        }

        function clearTargets() {
            ProFormaService.clearTargets();

            for (var i = 0; i < $scope.hhiDataPages.length; i++)
                for (var j = 0; j < $scope.hhiDataPages[i].length; j++) {
                    $scope.hhiDataPages[i][j].isTarget = false;
                    for (var k = 0; k < $scope.hhiDataPages[i][j].orgs.length; k++)
                        $scope.hhiDataPages[i][j].orgs[k].isTarget = false;
                }
        }




    }
})();
;
(function () {
    'use strict';

    angular
      .module('app')
		.controller('AdvMarketListMapController', AdvMarketListMapController);

	AdvMarketListMapController.$inject = ['$scope', '$state', '$stateParams', 'AdvMarketsService', 'leafletData', 'leafletBoundsHelpers', 'MarketsService', 'AdvBranchesService', 'MarketMapService', 'toastr', '$timeout', 'marketIdList', 'fullScreenMode'];

	function AdvMarketListMapController($scope, $state, $stateParams, AdvMarketsService, leafletData, leafletBoundsHelpers, MarketsService, AdvBranchesService, MarketMapService, toastr, $timeout, marketIdList, fullScreenMode)
	{
		$scope.marketMap = null;
		$scope.hasShapeData = false;
		var branchData = null;
		var allBranchData = null;
		$scope.markers = [];
		var year = (new Date()).getFullYear();
		var mapBoxAndOpenMapsAttribution = '&copy;' + year + ' <a href="https://www.mapbox.com/about/maps/">MapBox</a> &copy;' + year + ' <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>';
		var cssAdded = false;
		var mouseOverTimeout = null;
		var mapRestoreHeight = null;
		var mapRestoreWidth = null;


		angular.extend($scope, {
			marketsLoaded: false,
			loadMarkets: loadMarkets,
			marketDisplayInfo: {},
			isMapShapeCurrent: true,
			leafletData: leafletData,
			mapReady: false,
			center: {},
			geoJson: {},
			layers: {
				overlays: {}
			},
			bounds: null,
			setMapStyle: setMapStyle,
			markers: {},
			hoveredMarket: null,
			tiles: {},
			closeMap: closeMap,
			toggleMapFullScreen: toggleMapFullScreen,
			displayMapFullScreen: false
		});		

		activate();


		function activate() {
			if (!$scope.marketsLoaded) {
				setMapStyle();
				loadMarkets();
				setupEvents();			
			}

			if (fullScreenMode) {
				//$timeout(function () { $scope.toggleMapFullScreen() }, 800);				
			}

			//$scope.$watch('marketLoaded', function (dataLoaded) {
			//	if (dataLoaded) {
			//		populateMap();
			//	}
			//});
		}

		function toggleMapFullScreen() {
			$scope.displayMapFullScreen = !$scope.displayMapFullScreen;
			if ($scope.displayMapFullScreen) {
				if (mapRestoreHeight == null) { // set first time only
					mapRestoreHeight = $("#leafy").height();
					mapRestoreWidth = $("#leafy").width();
				} 
				$("#leafy").height($(window).height() - 90);
				$("#leafy").width($(window).width() - 27);
				
				$("#mapDisplayContainerBox").height($(window).height() - 68);
				$("#mapDisplayContainerBox").width($(window).width() - 24);
				$("#mapDisplayContainerBox").css('margin-left', -1 * (($(window).width() / 2) - (mapRestoreWidth / 2)));
				$("#mapDisplayContainerBox").addClass("fullScreenMap");
				$("#mapDisplayContainerBox #mapExpandCtrl .label").text('Smaller');
				

				//$("#leafy").addClass('fullScreenMap')
			}
			else {
				$("#leafy").height(mapRestoreHeight);
				$("#leafy").width(mapRestoreWidth - 2);
				$("#mapDisplayContainerBox").height(mapRestoreHeight);
				$("#mapDisplayContainerBox").width(mapRestoreWidth);
				$("#mapDisplayContainerBox").css('margin-left', 0);
				$("#mapDisplayContainerBox").removeClass("fullScreenMap");

				$("#mapDisplayContainerBox #mapExpandCtrl .label").text('Expand');			
			}

			leafletData.getMap()
				.then(function (map) {
					map.invalidateSize();
				});
		}

		function closeMap() {
			$scope.$dismiss();
		}

		function setupEvents() {
			$scope.$on("leafletDirectiveGeoJson.leafy.mouseout",
				function (ev, leafletPayload) {
					highlightViewedMarketMap(leafletPayload.leafletEvent.target, leafletPayload.leafletObject.feature, false);
				});	

			$scope.$on("leafletDirectiveGeoJson.leafy.mouseover",
				function (ev, leafletPayload) {
					highlightViewedMarketMap(leafletPayload.leafletEvent.target, leafletPayload.leafletObject.feature, true);
				});	

			$scope.$on("leafletDirectiveGeoJson.leafy.click", function (ev, leafletPayload) {
				var feature = leafletPayload.leafletObject.feature;
				$state.go("root.adv.markets.detail.definition", { market: feature.properties.marketId });
				closeMap();
			});

			$scope.$on('leafletDirectiveMap.leafy.load', function (event) {
				$timeout(function () { $scope.toggleMapFullScreen() }, 800);
			});
		}

		function highlightViewedMarketMap(layer, feature, showHighlight) {
			if (showHighlight) {
				mouseOverTimeout = $timeout(function () {
					$scope.hideMapMarketLink = true;
					$scope.hoveredMarket = feature.properties;
					layer.setStyle({
						weight: 3,
						color: "#595959",
						fillOpacity: 0.6,
						opacity: 1
					});
					layer.bringToFront();
				}, 10); // use timeout to avoid race condition with mouse outs from surrounding market shape layers
			}
			else {
				// no timeout here. On the mouse out we want it to happen asap so we don't mess with any other mouse over events..
				if (mouseOverTimeout != null) { $timeout.cancel(mouseOverTimeout);}
				$scope.hideMapMarketLink = false;
				$scope.hoveredMarket = null;
				layer.setStyle({
					weight: 2,
					color: "white",
					fillOpacity: 0.25
				});
			}
		}
		
		function setMapStyle() {
			$scope.tiles = {
				name: 'Counties, Roads & Cities',
				url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
				options: {
					apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
					mapid: 'circdk0r3001uganjch20akrs',
					attribution: mapBoxAndOpenMapsAttribution
				},
				type: 'xyz',
				data: {
					counties: true,
					roads: true,
					cities: true
				}
			}
		}

		function loadMarkets() {
			$scope.marketsLoaded = false;
			AdvMarketsService.getMultpleMarkets(marketIdList)
				.then(function (result) {
					if (result.hasError || result.isTimeout) {
						toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
						return;
					}

					if (result.features && result.features.features && result.features.features.length > 0) {
						$scope.hasShapeData = true;
					}

					var colors = ["red", "orange", "yellow", "green", "purple"];
					var fullBbox = result.bbox;

					var geoJson = {
						data: result.features,
						style: function (feature) {
							return {
								fillColor: colors[feature.properties.index % colors.length],
								weight: 2,
								opacity: 0.5,
								color: "white",
								dashArray: "3",
								fillOpacity: 0.25
							}
						},
						resetStyleOnMouseout: true
					};
					$scope.geoJson = geoJson;

					if (geoJson && fullBbox) {
						var bounds = leafletBoundsHelpers.createBoundsFromArray([
							[fullBbox[1], fullBbox[0]],
							[fullBbox[3], fullBbox[2]]
						]);
					}
					if ($scope.hasShapeData) {
						$scope.bounds = bounds;
						$scope.center = {};
					}
					else {
						$scope.bounds = null;
						$scope.mapReady = true;
					}

					$scope.marketsLoaded = true;
				});
			}
		}
})();

    



;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketRecodeController', AdvMarketRecodeController);

    AdvMarketRecodeController.$inject = ['$scope', '$rootScope', '$state', '$uibModal', '$stateParams', 'StatesService', 'AdvMarketsService', 'toastr', 'Dialogger'];

    function AdvMarketRecodeController($scope, $rootScope, $state, $uibModal, $stateParams, StatesService, AdvMarketsService, toastr, Dialogger) {


        angular.extend($scope,
        {
            recodeTitle: getRecodeTitle($state.current),
            states: [],
            runDate: new Date(),
            statesLoaded: false,
            stopSpinner: false,
            marketByStateData: [],
            marketByStateBackup: [],
            marketByStateDataLoaded: false,
            totalMarketByStateItems: 0,
            marketByStateItemsPerPage: 50,
            currenMarketByStatePage: 1,
            marketByStatePageSize: 30,
            marketByStateDataPages: 0,
            marketByState: { state: null },
            gridDisplay: false,
            row_marketId: 0,
            marketUpdated: false,
            errorMessage: "",
            marketByStateSubmit: handlemarketByStateSearch
        });

        activate();

        function activate() {
            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
        }

        function getRecodeTitle(stateToCheck) {
            $scope.$parent.$parent.marketName = "";
            return stateToCheck.data.title;
        }

        $scope.DeleteCityMarket = function (cityId, stateId) {

            var confirmDialog = Dialogger.confirm("Are you sure you wish to DELETE this City from this Market?");

            confirmDialog.then(function (confirmed) {
                if (confirmed) {
                    AdvMarketsService.getDeleteRecodeMarketCity(cityId, stateId).then(function (data) {
                        $scope.gridDisplay = true;
                        $scope.stopSpinner = false;
                        $scope.marketByStateData = data.marketDataObject;
                        $scope.marketByStateDataLoaded = true;
                        if (data.recNotSaved == false)
                            toastr.success("City deleted from Market sucessfully!");
                        else
                            toastr.error("Error deleting City.", data.errorMessage || "Please try again or contact support. Sorry about that.");
                    });
                }
            });

        }

        $scope.marketsHaveBeenChanged = function () {

            var changed = false;
            
            $.each($scope.marketByStateData,
                function(i, e) {
                    if (_.find($scope.marketByStateBackup,
                        { marketCityId: e.marketCityId, marketId: e.marketId }) == null)
                        changed = true;
                });

            return changed;
        };

        $scope.Resetform = function ()
        {
            if ($scope.marketsHaveBeenChanged()) {

                var confirmDialog = Dialogger.confirm("You have unsaved changes. Continue?");

                confirmDialog.then(function(confirmed) {
                    if(confirmed)
                        $scope.resetFormValues();
                });
            } else {
                $scope.resetFormValues();
            }
        };


        $scope.resetFormValues = function() {
            $scope.gridDisplay = false;
            $scope.marketByState.state = null;
            $scope.marketByStateData = [];
            $scope.marketByStateDataLoaded = false;
            $scope.totalMarketByStateItems = 0;
            $scope.marketByStateItemsPerPage = 50;
            $scope.currenMarketByStatePage = 1;
            $scope.marketByStatePageSize = 30;
            $scope.marketByStateDataPages = 0;
            $scope.marketByStateDataLoaded = false;
        };

        $scope.SaveFacilities = function () {

            $scope.stopSpinner = true;

            AdvMarketsService
                .updateMarketCities($scope.marketByStateData)
                .then(function (data) {
                    
                    if (!data.ErrorFlag)
                        toastr.success("Updated Recode Market data sucessfully!");
                    else
                        toastr.error("Error updating Recode Market data.", data.errorMessage || "Please try again or contact support. Sorry about that.");

                    handlemarketByStateSearch();
                });

        };

        $scope.openAddCityToMarket = function (stateId) {

            if ($scope.marketsHaveBeenChanged()) {

                var confirmDialog = Dialogger.confirm("You have unsaved changes. Continue?");

                confirmDialog.then(function (confirmed) {
                    if (confirmed)
                        AdvMarketsService.openAddCityToMarket(stateId);
                });
            } else {
                AdvMarketsService.openAddCityToMarket(stateId);
            }

        }


        $scope.$on('new-city-added', function (event, data) {
         
            handlemarketByStateSearch();

        });


        function handlemarketByStateSearch() {

            $scope.stopSpinner = true;
            $scope.marketByStateDataLoaded = false;
            AdvMarketsService
                .getMarketsByState($scope.marketByState.state.stateId)
                .then(function (data) {

                    $scope.gridDisplay = true;
                    $scope.stopSpinner = false;
                    $scope.marketByStateData = data;
                    $scope.totalMarketByStateItems = $scope.marketByStateData.length;
                    $scope.marketByStateDataPages = _.chunk($scope.marketByStateData, $scope.marketByStateItemsPerPage);
                    $scope.marketByStateDataLoaded = true;

                    $scope.marketByStateBackup = _.map($scope.marketByStateData,
                        function(e) { return { marketCityId: e.marketCityId, marketId: e.marketId }; });

                });
        }

    }



    angular
      .module('app')
        .filter('marketByStateFilter', function () {
            return function (dataArray, searchTerm) {
                if (!dataArray) return;
                if (searchTerm.$ == undefined) {
                    return dataArray;
                } else {
                    var term = searchTerm.$.toLowerCase();
                    return dataArray.filter(function (item) {
                        return checkVal(item.countyName, term)
                            || checkVal(item.marketId.toString(), term)
                            || checkVal(item.cityName, term)
                            || checkVal(item.stateName, term)
                            || checkVal(item.districtId.toString(), term)
                            || checkVal(item.countyId.toString(), term)
                            || checkVal(item.stateFIPSId.toString(), term);
                    });
                }
            }

            function checkVal(val, term) {
                if (val == null || val == undefined)
                    return false;

                return val.toLowerCase().indexOf(term) > -1;
            }
        });

})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketsByCountyController', AdvMarketsByCountyController);

    AdvMarketsByCountyController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvMarketsService', '$log'];

    function AdvMarketsByCountyController($scope, $rootScope, $state, StatesService, AdvMarketsService, $log) {
        angular.extend($scope, {
            subTitle: getSubTitle($state.current),
            states: [],
            statesLoaded: false,

            //districtsWithStates: [],
            //districtsWithStatesReady: false,
            //districtStates: [],

            //stateAndDistrictData: [],
            //stateAndDistrictDataLoaded: false,
            //stateAndDistrict: { state: null, district: null },
            //stateAndDistrictSubmit: handleStateAndDistrictSearch,

            stateAndCountyData: [],
            stateAndCountyDataLoaded: false,
            stateAndCounty: { state: null },
            stateAndCountySubmit: handleStateAndCountySearch

            //stateAndMarketNumData: [],
            //stateAndMarketNumDataLoaded: false,
            //stateAndMarketNum: { state: null },
            //stateAndMarketNumSubmit: handleStateAndMarketNumSearch,

            //districtChanged: districtChanged
        });

        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.subTitle = getSubTitle(toState);
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

            //StatesService.getStatesWithDistricts().then(function (result) {
            //    //$log.info("getStatesWithDistricts", result);
            //    $scope.districtsWithStates = result;
            //    $scope.districtsWithStatesReady = true;
            //});
        }

        function getSubTitle(stateToCheck) {
            return stateToCheck.data.h1;
        }

        //function handleStateAndDistrictSearch() {
        //    $log.info("handleStateAndDistrictSearch", $scope.stateAndDistrict);

        //    $scope.stateAndDistrictDataLoaded = false;
        //    AdvMarketsService
        //        .getMarketsByStateAndDistrict($scope.stateAndDistrict.state.stateId, $scope.stateAndDistrict.district)
        //        .then(function (data) {
        //            $scope.stateAndDistrictData = data;
        //            $scope.stateAndDistrictDataLoaded = true;
        //        });
        //}

        function handleStateAndCountySearch() {
            $log.info($scope.stateAndCounty);

            $scope.stateAndCountyDataLoaded = false;
            AdvMarketsService
                .getMarketsByStateAndCounty($scope.stateAndCounty.state.stateId)
                .then(function (data) {
                    $scope.stateAndCountyData = data;
                    $scope.stateAndCountyDataLoaded = true;
                });
        }

        //function handleStateAndMarketNumSearch() {
        //    $log.info($scope.stateAndMarketNum);

        //    $scope.stateAndMarketNumDataLoaded = false;
        //    AdvMarketsService
        //        .getMarketsByStateAndMarketNo($scope.stateAndMarketNum.state.stateId)
        //        .then(function (data) {
        //            $scope.marketData = formatDataForMarkets(data);
        //            $scope.stateAndMarketNumDataLoaded = true;
        //        });
        //}

        function formatDataForMarkets(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                //if (rec.marketId <= 0) continue;
                var county = { name: rec.counties[0].name, state: rec.counties[0].state, district: rec.counties[0].district };
                var market = _.find(newData, { marketId: rec.marketNumber });

                if (typeof market == "undefined") {//already added market to data variable?
                    market = {
                        marketId: rec.marketNumber,
                        marketName: rec.marketName,
                        marketDescr: rec.marketDescr,
                        district: rec.districtDefined,
                        countyList: [county]

                    }; //create new
                    newData.push(market);
                } else
                    market.countyList.push(county);
            }
            return newData;
        }

        //function districtChanged(districtId) {
        //    //$log.info("districtId", districtId);

        //    var data = $scope.districtsWithStates[districtId].states;
        //    $scope.stateAndDistrictDataLoaded = false;
        //    $scope.districtStates = data;
        //}
    }


})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketsByDistrictController', AdvMarketsByDistrictController);

    AdvMarketsByDistrictController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvMarketsService', '$log'];

    function AdvMarketsByDistrictController($scope, $rootScope, $state, StatesService, AdvMarketsService, $log) {
        angular.extend($scope, {
            subTitle: getSubTitle($state.current),
            states: [],
            statesLoaded: false,

            districtsWithStates: [],
            districtsWithStatesReady: false,
            districtStates: [],

            stateAndDistrictData: [],
            stateAndDistrictDataLoaded: false,
            stateAndDistrict: { state: null, district: null },
            stateAndDistrictSubmit: handleStateAndDistrictSearch,

            //stateAndCountyData: [],
            //stateAndCountyDataLoaded: false,
            //stateAndCounty: { state: null },
            //stateAndCountySubmit: handleStateAndCountySearch,

            //stateAndMarketNumData: [],
            //stateAndMarketNumDataLoaded: false,
            //stateAndMarketNum: { state: null },
            //stateAndMarketNumSubmit: handleStateAndMarketNumSearch,

            districtChanged: districtChanged
        });

        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.subTitle = getSubTitle(toState);
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

            StatesService.getStatesWithDistricts().then(function (result) {
                //$log.info("getStatesWithDistricts", result);
                $scope.districtsWithStates = result;
                $scope.districtsWithStatesReady = true;
            });
        }

        function getSubTitle(stateToCheck) {
            return stateToCheck.data.h1;
        }

        function handleStateAndDistrictSearch() {
            $log.info("handleStateAndDistrictSearch", $scope.stateAndDistrict);

            $scope.stateAndDistrictDataLoaded = false;
            AdvMarketsService
                .getMarketsByStateAndDistrict($scope.stateAndDistrict.state.stateId, $scope.stateAndDistrict.district)
                .then(function (data) {
                    $scope.stateAndDistrictData = data;
                    $scope.stateAndDistrictDataLoaded = true;
                });
        }

        //function handleStateAndCountySearch() {
        //    $log.info($scope.stateAndCounty);

        //    $scope.stateAndCountyDataLoaded = false;
        //    AdvMarketsService
        //        .getMarketsByStateAndCounty($scope.stateAndCounty.state.stateId)
        //        .then(function (data) {
        //            $scope.stateAndCountyData = data;
        //            $scope.stateAndCountyDataLoaded = true;
        //        });
        //}

        //function handleStateAndMarketNumSearch() {
        //    $log.info($scope.stateAndMarketNum);

        //    $scope.stateAndMarketNumDataLoaded = false;
        //    AdvMarketsService
        //        .getMarketsByStateAndMarketNo($scope.stateAndMarketNum.state.stateId)
        //        .then(function (data) {
        //            $scope.marketData = formatDataForMarkets(data);
        //            $scope.stateAndMarketNumDataLoaded = true;
        //        });
        //}

        //function formatDataForMarkets(origData) {
        //    var newData = [];
        //    for (var i = 0; i < origData.length; i++) {
        //        var rec = origData[i];
        //        if (rec.marketId <= 0) continue;
        //        var county = { name: rec.counties[0].name, state: rec.counties[0].state, district: rec.counties[0].district };
        //        var market = _.find(newData, { marketId: rec.marketNumber });

        //        if (typeof market == "undefined") {//already added market to data variable?
        //            market = {
        //                marketId: rec.marketNumber,
        //                marketName: rec.marketName,
        //                marketDescr: rec.marketDescr,
        //                district: rec.districtDefined,
        //                countyList: [county]

        //            }; //create new
        //            newData.push(market);
        //        } else
        //            market.countyList.push(county);
        //    }
        //    return newData;
        //}

        function districtChanged(districtId) {
            //$log.info("districtId", districtId);

            var data = $scope.districtsWithStates[districtId].states;
            $scope.stateAndDistrictDataLoaded = false;
            $scope.districtStates = data;
        }
    }


})();
;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketsByMarketController', AdvMarketsByMarketController);

    AdvMarketsByMarketController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvMarketsService', '$log'];

    function AdvMarketsByMarketController($scope, $rootScope, $state, StatesService, AdvMarketsService, $log) {
        angular.extend($scope, {
            subTitle: getSubTitle($state.current),
            states: [],
            statesLoaded: false,

            //districtsWithStates: [],
            //districtsWithStatesReady: false,
            //districtStates: [],

            //stateAndDistrictData: [],
            //stateAndDistrictDataLoaded: false,
            //stateAndDistrict: { state: null, district: null },
            //stateAndDistrictSubmit: handleStateAndDistrictSearch,

            //stateAndCountyData: [],
            //stateAndCountyDataLoaded: false,
            //stateAndCounty: { state: null },
            //stateAndCountySubmit: handleStateAndCountySearch,

            stateAndMarketNumData: [],
            stateAndMarketNumDataLoaded: false,
            stateAndMarketNum: { state: null },
            stateAndMarketNumSubmit: handleStateAndMarketNumSearch

            //districtChanged: districtChanged
        });

        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.subTitle = getSubTitle(toState);
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

            //StatesService.getStatesWithDistricts().then(function (result) {
            //    //$log.info("getStatesWithDistricts", result);
            //    $scope.districtsWithStates = result;
            //    $scope.districtsWithStatesReady = true;
            //});
        }

        function getSubTitle(stateToCheck) {
            return stateToCheck.data.h1;
        }

        //function handleStateAndDistrictSearch() {
        //    $log.info("handleStateAndDistrictSearch", $scope.stateAndDistrict);

        //    $scope.stateAndDistrictDataLoaded = false;
        //    AdvMarketsService
        //        .getMarketsByStateAndDistrict($scope.stateAndDistrict.state.stateId, $scope.stateAndDistrict.district)
        //        .then(function (data) {
        //            $scope.stateAndDistrictData = data;
        //            $scope.stateAndDistrictDataLoaded = true;
        //        });
        //}

        //function handleStateAndCountySearch() {
        //    $log.info($scope.stateAndCounty);

        //    $scope.stateAndCountyDataLoaded = false;
        //    AdvMarketsService
        //        .getMarketsByStateAndCounty($scope.stateAndCounty.state.stateId)
        //        .then(function (data) {
        //            $scope.stateAndCountyData = data;
        //            $scope.stateAndCountyDataLoaded = true;
        //        });
        //}

        function handleStateAndMarketNumSearch() {
            $log.info($scope.stateAndMarketNum);

            $scope.stateAndMarketNumDataLoaded = false;
            AdvMarketsService
                .getMarketsByStateAndMarketNo($scope.stateAndMarketNum.state.stateId)
                .then(function (data) {
                    $scope.marketData = formatDataForMarkets(data);
                    $scope.stateAndMarketNumDataLoaded = true;
                });
        }

        function formatDataForMarkets(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
               // if (rec.marketId <= 0) continue;
                var county = { name: rec.counties[0].name, state: rec.counties[0].state, district: rec.counties[0].district };
                var market = _.find(newData, { marketId: rec.marketNumber });

                if (typeof market == "undefined") {//already added market to data variable?
                    market = {
                        marketId: rec.marketNumber,
                        marketName: rec.marketName,
                        marketDescr: rec.marketDescr,
                        district: rec.districtDefined,
                        countyList: [county]

                    }; //create new
                    newData.push(market);
                } else
                    market.countyList.push(county);
            }
            return newData;
        }

        //function districtChanged(districtId) {
        //    //$log.info("districtId", districtId);

        //    var data = $scope.districtsWithStates[districtId].states;
        //    $scope.stateAndDistrictDataLoaded = false;
        //    $scope.districtStates = data;
        //}
    }


})();;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketsByStateController', AdvMarketsByStateController);

    AdvMarketsByStateController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvMarketsService', '$log'];

    function AdvMarketsByStateController($scope, $rootScope, $state, StatesService, AdvMarketsService, $log) {
        angular.extend($scope, {
            subTitle: getSubTitle($state.current),
            states: [],
            statesLoaded: false,

            districtsWithStates: [],
            districtsWithStatesReady: false,
            districtStates: [],

            stateAndDistrictData: [],
            stateAndDistrictDataLoaded: false,
            stateAndDistrict: { state: null, district: null },
            stateAndDistrictSubmit: handleStateAndDistrictSearch,

            stateAndCountyData: [],
            stateAndCountyDataLoaded: false,
            stateAndCounty: { state: null },
            stateAndCountySubmit: handleStateAndCountySearch,

            stateAndMarketNumData: [],
            stateAndMarketNumDataLoaded: false,
            stateAndMarketNum: { state: null },
            stateAndMarketNumSubmit: handleStateAndMarketNumSearch,

            districtChanged: districtChanged
        });

        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.subTitle = getSubTitle(toState);
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

            StatesService.getStatesWithDistricts().then(function (result) {
                //$log.info("getStatesWithDistricts", result);
                $scope.districtsWithStates = result;
                $scope.districtsWithStatesReady = true;
            });
        }

        function getSubTitle(stateToCheck) {
            return stateToCheck.data.h1;
        }

        function handleStateAndDistrictSearch() {
            $log.info("handleStateAndDistrictSearch", $scope.stateAndDistrict);

            $scope.stateAndDistrictDataLoaded = false;
            AdvMarketsService
                .getMarketsByStateAndDistrict($scope.stateAndDistrict.state.stateId, $scope.stateAndDistrict.district)
                .then(function (data) {
                    $scope.stateAndDistrictData = data;
                    $scope.stateAndDistrictDataLoaded = true;
                });
        }

        function handleStateAndCountySearch() {
            $log.info($scope.stateAndCounty);

            $scope.stateAndCountyDataLoaded = false;
            AdvMarketsService
                .getMarketsByStateAndCounty($scope.stateAndCounty.state.stateId)
                .then(function (data) {
                    $scope.stateAndCountyData = data;
                    $scope.stateAndCountyDataLoaded = true;
                });
        }

        function handleStateAndMarketNumSearch() {
            $log.info($scope.stateAndMarketNum);

            $scope.stateAndMarketNumDataLoaded = false;
            AdvMarketsService
                .getMarketsByStateAndMarketNo($scope.stateAndMarketNum.state.stateId)
                .then(function (data) {
                    $scope.marketData = formatDataForMarkets(data);
                    $scope.stateAndMarketNumDataLoaded = true;
                });
        }

        function formatDataForMarkets(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                //if (rec.marketId <= 0) continue;
                var county = { name: rec.counties[0].name, state: rec.counties[0].state, district: rec.counties[0].district };
                var market = _.find(newData, { marketId: rec.marketNumber });

                if (typeof market == "undefined") {//already added market to data variable?
                    market = {
                        marketId: rec.marketNumber,
                        marketName: rec.marketName,
                        marketDescr: rec.marketDescr,
                        district: rec.districtDefined,
                        countyList: [county]

                    }; //create new
                    newData.push(market);
                } else
                    market.countyList.push(county);
            }
            return newData;
        }

        function districtChanged(districtId) {
            //$log.info("districtId", districtId);

            var data = $scope.districtsWithStates[districtId].states;
            $scope.stateAndDistrictDataLoaded = false;
            $scope.districtStates = data;
        }
    }


})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketsController', AdvMarketsController);

    AdvMarketsController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvMarketsService', '$log'];

    function AdvMarketsController($scope, $rootScope, $state, StatesService, AdvMarketsService, $log) {
        angular.extend($scope, {
            isIndex: isOnIndexPage($state.current),

        });        
        
        $scope.criteria = {
            name: null,
            county: null,
            city: null,
            number: null,
            state: null,
            zip: null,
            district: null
        }

        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.isIndex = isOnIndexPage(toState);
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });
        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.markets";
        }
    }
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketSearchController', AdvMarketSearchController);

	AdvMarketSearchController.$inject = ['$scope', '$state', 'StatesService', '$stateParams', '$timeout', '$templateCache', 'AdvMarketsService', 'UserData', 'uiGridConstants', 'uiGridGroupingConstants', 'store', '$window', 'toastr', 'Dialogger', '$uibModal'];

	function AdvMarketSearchController($scope, $state, StatesService, $stateParams, $timeout, $templateCache, AdvMarketsService, UserData, uiGridConstants, uiGridGroupingConstants, store, $window, toastr, Dialogger, $uibModal) {
        angular.extend($scope, {
            criteriaValue: [],
            status: [],
            stateCopyData: [],
            newState: [],
            districtChanged: districtChanged
        });

		var marketMapMaxCount = 500;
		var marketMapWarnCount = 200;


        var marketsData, statesOrCountiesData;
        $scope.districtsWithStates = [];
        $scope.data = [];
        $scope.searchByMarketNumber = false;
        $scope.originaldata = [];
        $scope.status.isOpen = true;
        $scope.loading = false;
        $scope.hiddeCriteria = false;
        $scope.searchCriteria = false;
        $scope.changedCriteria = false;
        $scope.countiesCount = 0;
        $scope.newcountiesCount = 0;
        $scope.resultMarketIds = [];
        var storeKey = 'advmarketSearch';

        $scope.totalItems = 0;
        $scope.ItemsPerPage = 30;

        $scope.NoRecord = false;
		$scope.instPageSize = 30;

		$scope.searchMapEnabled = false;

		$scope.loadMarketsMap = function () {
			$uibModal.open({
				animation: true,
				modal: true,
				size: 'xlg',
				keyboard: false,
				backdrop: 'static',
				templateUrl: '/AppJs/advanced/markets/views/_mapSearchResults.html',
				controller: 'AdvMarketListMapController',
				resolve: {
					marketIdList: function () {
						return $scope.resultMarketIds;
                    },
                    fullScreenMode: true
				}
			})
		}

		$scope.showMarketSearchMap = function () {

			if ($scope.resultMarketIds.length > marketMapMaxCount) {
				// to many markets for mapping
				var mapMsgText = "<b>WARNING!</b> <br />Your search returned <b>more than " + marketMapMaxCount + " markets</b>. <b>Map creation may fail; or may take several minutes to complete.</b> <br /><br />You may continue. However, if your computer does not contain sufficient memory, your map may not display. <br /><br />Click OK to continue creating the map. <br />Click Cancel to exit.";
				var confirmDialog = Dialogger.confirm(mapMsgText);
				confirmDialog.then(function (confirmed) {
					if (confirmed) {
						$scope.loadMarketsMap();
					}
				});
			}
			else if ($scope.resultMarketIds.length >= marketMapWarnCount) {
				var confirmDialog = Dialogger.confirm("Notice: Your search found a large number of markets. It may take a minute or more for your map to complete. Please be patient. <br /><br /> Click OK to continue creating your map.");
				confirmDialog.then(function (confirmed) {
					if (confirmed) {
						$scope.loadMarketsMap();
					}
				});
			}
			else {
                $scope.loadMarketsMap();                
			}
		}

        $scope.criteriaEntered = function () {
            $scope.criteria.county == ($scope.criteria.count == 14 ? null : $scope.criteria.count);

			return ($scope.criteria.name != null && $scope.criteria.name != '') ||
				($scope.criteria.number != null && $scope.criteria.number != '') ||
                $scope.criteria.state != null ||
                $scope.criteria.county != null ||
				($scope.criteria.zip != null && $scope.criteria.zip != '') ||
                $scope.criteria.city != null ||
				($scope.criteria.district != null && $scope.criteria.district != '' && $scope.criteria.district <= 12);
        };
        $scope.saveMarket = function (market) {
            UserData.markets.save(market);
        };
        $scope.isSavedMarket = function (id) {
            return UserData.markets.isSaved(id);
        };
        $scope.removeMarket = function (market) {
            UserData.markets.remove(market.marketId);
        };
        $scope.showClearLink = function () {
            return UserData.markets.any(marketsData);
        };
        $scope.clearMarkets = function () {
            UserData.markets.remove(marketsData);
        }
        $scope.toggleMarket = function (market) {
            var id = market.marketId;
            if (UserData.markets.isSaved(id))
                UserData.markets.remove(id);
            else
                UserData.markets.save(market);
        };
        $scope.clearCriteria = function () {
            $scope.criteria.name = null;
            $scope.criteria.county = null;
            $scope.criteria.city = null;
            $scope.criteria.number = null;
            $scope.criteria.state = null;
            $scope.criteria.zip = null;
            $scope.criteria.district = null;
            $scope.dataReadyMarketNumber = false;
            $scope.dataReadyMarketName = false;
            $scope.dataReadyCountyName = false;
            $scope.dataReadyDistrict = false;
            $scope.dataReadyState = false;
            $scope.states = $scope.stateCopyData;
            $scope.totalItems = 0;
            store.remove(storeKey);
            $scope.searchCriteria = false;
            window.document.getElementById("name").focus();
        };
        $scope.displayCriteria = function (value) {
            $scope.hiddeCriteria = !value;

        };

        $scope.setTableDisplay = function (tableDisplay) {
            $scope.tableDisplay = tableDisplay;
            $scope.sortDesc = false;
            switch ($scope.tableDisplay) {
                case "byCountyName":
                    $scope.countiesCount = 0;
                    marketsData = formatDataForCountyName($scope.originaldata);
                    $scope.data = marketsData;
                    $scope.totalItems = $scope.data.length;
                    // $scope.marketDataPages = _.chunk($scope.data, $scope.ItemsPerPage);
                    $scope.dataReadyMarketNumber = false;
                    $scope.dataReadyMarketName = false;
                    $scope.dataReadyDistrict = false;
                    $scope.dataReadyState = false;
                    $scope.dataReadyCountyName = true;
                    $scope.loading = false;
                    // $scope.hiddeCriteria =  true
                    break;
                case "byState":
                    $scope.countiesCount = 0;
                    marketsData = formatDataForState($scope.originaldata);
                    $scope.data = marketsData;
                    $scope.totalItems = $scope.data.length;
                    //  $scope.marketDataPages = _.chunk($scope.data, $scope.ItemsPerPage);
                    $scope.dataReadyMarketNumber = false;
                    $scope.dataReadyMarketName = false;
                    $scope.dataReadyDistrict = false;
                    $scope.dataReadyCountyName = false;
                    $scope.dataReadyState = true;
                    $scope.loading = false;
                    // $scope.hiddeCriteria = true
                    break;
                case "byMarketNumber":
                    $scope.countiesCount = 0;
                    marketsData = formatDataForMarketNumber($scope.originaldata);
                    $scope.data = marketsData;
                    $scope.totalItems = $scope.data.length;
                    // $scope.marketDataPages = _.chunk($scope.data, $scope.ItemsPerPage);
                    $scope.dataReadyMarketName = false;
                    $scope.dataReadyState = false;
                    $scope.dataReadyDistrict = false;
                    $scope.dataReadyCountyName = false;
                    $scope.dataReadyMarketNumber = true;
                    $scope.loading = false;
                    // $scope.hiddeCriteria = true
                    break;
                case "byMarketName":
                    $scope.countiesCount = 0;
                    marketsData = formatDataForMarketName($scope.originaldata);
                    $scope.data = marketsData;
                    $scope.totalItems = $scope.data.length;
                    // $scope.marketDataPages = _.chunk($scope.data, $scope.ItemsPerPage);
                    $scope.dataReadyMarketNumber = false;
                    $scope.dataReadyState = false;
                    $scope.dataReadyCountyName = false;
                    $scope.dataReadyDistrict = false;
                    $scope.dataReadyMarketName = true;
                    $scope.loading = false;
                    // $scope.hiddeCriteria = true
                    break;
                    //formatDataForDistrict
                case "byDistrict":
                    marketsData = formatDataForDistrict($scope.originaldata);
                    $scope.data = marketsData;
                    $scope.totalItems = $scope.data.length;
                    // $scope.marketDataPages = _.chunk($scope.data, $scope.ItemsPerPage);
                    $scope.dataReadyMarketNumber = false;
                    $scope.dataReadyState = false;
                    $scope.dataReadyCountyName = false;
                    $scope.dataReadyMarketName = false;
                    $scope.dataReadyDistrict = true;
                    $scope.loading = false;
                    // $scope.hiddeCriteria = true
                    break;
            }

        };

        $scope.PageCount = function () {
            return Math.ceil($scope.data.length / $scope.ItemsPerPage);
        };


        activate();

        $scope.UpdateCountysAndCitys = function () {
            $scope.criteria.city = null;
            $scope.criteria.county = null;

            var data = {
				stateFIPSId: $scope.criteria.state ? $scope.criteria.state.fipsId : null
            };
            StatesService.getCityNames(data).then(function (result) {
                $scope.criteria.state.cities = result;
            });

            StatesService.getCountySummaries(data).then(function (result) {
                $scope.criteria.state.counties = result;
            });

        }

        function activate() {
            window.document.getElementById("name").focus();
            var data = {
                includeDC: true,
                includeTerritories: true
            };
            StatesService.getStateSummaries(data).then(function (result) {
                $scope.states = result;
                $scope.stateCopyData = result;
                $scope.statesLoaded = true;
                $scope.stateCopyData = result;
            });



            StatesService.getStatesWithDistricts().then(function (result) {
                //$log.info("getStatesWithDistricts", result);
                $scope.districtsWithStates = result;
                $scope.districtsWithStatesReady = true;
            });

            $scope.isNumeric = function (evt) {
                var theEvent = evt || window.event;
                var key = theEvent.keyCode || theEvent.which;
                key = String.fromCharCode(key);
                var regex = /^[0-9]$/;
                if (!regex.test(key)) {
                    theEvent.returnValue = false;
                    if (theEvent.preventDefault) theEvent.preventDefault();

                }
            };

            $scope.SearchSubmit = function () {
                // $state.go('^.list', data);    
				$scope.searchMapEnabled = false;
                store.set(storeKey, $scope.criteria);
                getSearchData();
            };

            if ($scope.statesLoaded) {
                $scope.criteria = store.get(storeKey);
                if ($scope.criteria != null) {
                    if ($scope.criteria.number == null ||
                        $scope.criteria.number == "")
                        getSearchData();
                }
            }
        }
        function buildCreteriaValue(data) {

            $scope.criteriaValue = {
                name: data.marketname,
                number: data.marketnumber,
                district: data.district,
                state: data.state ? $scope.criteria.state.name : null,
                county: data.county ? $scope.criteria.county.countyName : null,
                city: data.city ? $scope.criteria.city.name : null,
                zip: data.zip
            }
        }
        function getSearchData() {
            $scope.loading = true;
            $scope.contProcessing = true;

            if ($scope.criteria.number != null) {
                if (($scope.criteria.number.toString().indexOf(',') > -1)) {
                    toastr.error("You cannot enter multiple Market Numbers!");
                    $scope.contProcessing = false;
                    $scope.loading = false;
                }
            }



            if ($scope.contProcessing == true)
            {
                var data = {
                    marketname: $scope.criteria.name,
                    marketnumber: ($scope.criteria.number == "" ? null : $scope.criteria.number),
                    district: $scope.criteria.district,
                    state: $scope.criteria.state ? $scope.criteria.state.fipsId : null,
                    county: $scope.criteria.county ? $scope.criteria.county.countyId : null,
                    city: $scope.criteria.city ? $scope.criteria.city.name : null,
                    zip: $scope.criteria.zip
                };

                $scope.searchParams = {
                    marketName: (data.marketname == "" ? null : data.marketname),
                    marketNumber: (data.marketnumber == "" ? null : data.marketnumber),
                    districtId: (data.district == 14 ? null : data.district),
                    stateId: (data.state == "" ? null : data.state),
                    countyId: (data.county == "" ? null : data.county),
                    cityName: (data.city == "" ? null : data.city),
                    zip: (data.zip == "" ? null : data.zip)
                };

                buildCreteriaValue(data);
                if (data.marketnumber != null)
                    $scope.searchByMarketNumber = true;
                else
                    $scope.searchByMarketNumber = false;

                AdvMarketsService
                    .getMarketsSearchData($scope.searchParams)
                    .then(function (result) {
                        //get data by county name
                        statesOrCountiesData = result;
                        $scope.originaldata = result;

                        marketsData = result;
                        $scope.data = result;

                        $scope.totalItems = $scope.data.length;
                        if ($scope.totalItems == 0) {
                            $scope.NoRecord = true;
                            $scope.dataReadyMarketNumber = false;
                            $scope.dataReadyMarketName = false;
                            $scope.dataReadyCountyName = false;
                            $scope.dataReadyDistrict = false;
                            $scope.dataReadyState = false;
                            $scope.loading = false;
                            return;
                        }
                        else {
                            $scope.NoRecord = false;
                            $scope.searchCriteria = true;
							$scope.changedCriteria = true;
                        }

                        if ($scope.searchByMarketNumber)
                            goToMarketDefinition();

                        setTableData($scope.searchParams);


                        if ($scope.criteria.district != null) {
                            districtChanged($scope.criteria.district);
                        }
                        $scope.newcountiesCount = 0;
                        $scope.resultMarketIds = [];  // for getting market counts
                        for (var x = 0; x < $scope.originaldata.length; x++) {
							var rec = $scope.originaldata[x];
							if (rec.hasGeom) {
								$scope.searchMapEnabled = true;
							}
                            if (rec.countyName != null) { $scope.newcountiesCount++; }
                            if ($scope.resultMarketIds.indexOf(rec.marketId) == -1) {$scope.resultMarketIds.push(rec.marketId);}
                        }
                    });
            }
            
        }
        function setTableData(params) {
            var displayready = false;

            if (params.marketName != null) {
                $scope.tableDisplay = "byMarketName";
                displayready = true;
            }
            if (params.districtId != null) {
                $scope.tableDisplay = "byMarketName";
                displayready = true;
            }
            if (params.zip != null) {
                $scope.tableDisplay = "byMarketName";
                displayready = true;
            }
            if (!displayready)
                $scope.tableDisplay = "byCountyName";


            $scope.setTableDisplay($scope.tableDisplay);
        }

        function goToMarketDefinition() {

            var data = {
                market: $scope.criteria.number
            };

            $state.go('^.detail.definition', data);
        }

        function districtChanged(districtId) {
            //$log.info("districtId", districtId);
            if ($scope.districtsWithStates.length == 0) return;
            if (districtId == 14) {
                $scope.states = $scope.stateCopyData;
            }
            else {
                $scope.newState = [];

                var data = $scope.districtsWithStates[districtId].states;

                for (var x = 0; x < data.length; x++) {
                    var st = data[x].stateName;
                    if (_.find($scope.stateCopyData, { name: st }))
                        $scope.newState[x] = _.find($scope.stateCopyData, { name: st });
                }

                $scope.states = $scope.newState;
            }
        }
        function GetStatesWhitDistricts() {

            StatesService.getStatesWithDistricts().then(function (result) {
                //$log.info("getStatesWithDistricts", result);
                $scope.districtsWithStates = result;
                $scope.districtsWithStatesReady = true;
            });
        }


        //this is form Market #
        function formatDataForCounties(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                // if (rec.marketId <= 0) continue;
                var county = { name: rec.countyName, statePostalCode: rec.statePostalCode, district: rec.districtId };
                var market = _.find(newData, { marketId: rec.marketId });


                if (typeof market == "undefined") {//already added market to data variable?
                    market = {
                        marketId: rec.marketId,
                        marketName: rec.marketName,
                        marketDescr: rec.description,
                        district: rec.districtId,
                        countyList: [county]

                    }; //create new
                    newData.push(market);
                } else
                    market.countyList.push(county);
            }
            return newData;
        }

        function formatDataForDistrict(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                // if (rec.marketId <= 0) continue;
                var market = { district: rec.districtId, statePostalCode: rec.statePostalCode, marketId: rec.marketId, marketName: rec.marketName, marketDescr: rec.description };

                var district = _.find(newData, { statePostalCode: rec.statePostalCode, name: rec.countyName });

                if (typeof district == "undefined") {//already added market to data variable?
                    district = {
                        district: rec.districtId,
                        statePostalCode: rec.statePostalCode,
                        name: rec.countyName,
                        marketList: [market]

                    }; //create new
                    newData.push(district);
                } else
                    district.marketList.push(market);
            }

            sort.arr.multisort(newData, ['district', 'name'], ['ASC', 'ASC']);

            return newData;
        }
        //filter by county name
        function formatDataForCountyName(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                //if (rec.marketId <= 0) continue;
                var market = { marketId: rec.marketId, statePostalCode: rec.statePostalCode, district: rec.districtId, marketDescr: rec.description, marketName: rec.marketName, };

                var county = _.find(newData, { name: rec.countyName, statePostalCode: rec.statePostalCode });

                if (typeof county == "undefined") {
                    county = {
                        name: rec.countyName,
                        marketId: rec.marketId,
                        statePostalCode: rec.statePostalCode,
                        marketList: [market]

                    }; //create new
                    newData.push(county);
                    $scope.countiesCount++;
                } else {
                    county.marketList.push(market);
                    // $scope.countiesCount++;
                }
            }
            sort.arr.sortby(newData, 'name', $scope.sortDesc, false);

            var l = newData.length;

            return newData;
        }
        function formatDataForState(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                // if (rec.marketId <= 0) continue;
                var market = { marketId: rec.marketId, statePostalCode: rec.statePostalCode, district: rec.districtId, marketDescr: rec.description, marketName: rec.marketName, };

                var county = _.find(newData, { statePostalCode: rec.statePostalCode, name: rec.countyName });

                if (typeof county == "undefined") {//already added market to data variable?
                    county = {
                        name: rec.countyName,
                        statePostalCode: rec.statePostalCode,
                        marketList: [market]

                    }; //create new
                    newData.push(county);
                    $scope.countiesCount++;
                } else {
                    county.marketList.push(market);
                    $scope.countiesCount++;
                }
            }


            sort.arr.multisort(newData, ['statePostalCode', 'name'], ['ASC', 'ASC']);

            return newData;
        }
        function formatDataForMarketNumber(origData) {
            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                //if (rec.marketId <= 0) continue;

                var county = { countyName: rec.countyName, statePostalCode: rec.statePostalCode, district: rec.districtId };
                var market = _.find(newData, { marketId: rec.marketId, marketName: rec.marketName });

                if (typeof market == "undefined") {//already added market to data variable?
                    market = {
                        marketId: rec.marketId,
                        marketName: rec.marketName,
                        statePostalCode: rec.statePostalCode,
                        description: rec.description,
                        data: [county],
                        subTableOptions: {
                            enableColumnMenus: false,
                            columnDefs: [
                                { name: "expando", displayName: "", width: 34, enableSorting: false },
                                { name: "County", field: "countyName", sort: { direction: uiGridConstants.ASC } },
                                { name: "State", field: "statePostalCode" }
                            ]
                        }
                    }; //create new
                    newData.push(market);
                    $scope.countiesCount++;
                } else {
                    market.data.push(county);
                    $scope.countiesCount++;
                }
            }

            sort.arr.multisort(newData, ['marketId', 'marketName'], ['ASC', 'ASC']);

            return newData;
        }
        function formatDataForMarketName(origData) {

            var newData = [];
            for (var i = 0; i < origData.length; i++) {
                var rec = origData[i];
                //if (rec.marketId <= 0) continue;

                var county = { countyName: rec.countyName, statePostalCode: rec.statePostalCode, district: rec.districtId };
                var market = _.find(newData, { marketName: rec.marketName, marketId: rec.marketId });

                if (typeof market == "undefined") {//already added market to data variable?
                    market = {
                        marketId: rec.marketId,
                        marketName: rec.marketName,
                        statePostalCode: rec.statePostalCode,
                        description: rec.description,
                        data: [county],
                        subTableOptions: {
                            enableColumnMenus: false,
                            columnDefs: [
                                { name: "expando", displayName: "", width: 34, enableSorting: false },
                                { name: "County", field: "countyName", sort: { direction: uiGridConstants.ASC } },
                                { name: "State", field: "statePostalCode" }
                            ]
                        }
                    }; //create new
                    newData.push(market);                    
                    $scope.countiesCount++;                    
                } else {
                    market.data.push(county);
                    $scope.countiesCount++;
                }
            }

            sort.arr.sortby(newData, 'marketName', $scope.sortDesc, false);

            return newData;
        }

        if (typeof sort == 'undefined') {
            var sort = {};
        }

        sort.arr = {
            /**
        * Function to sort multidimensional array
        * 
        * param {array} [arr] Source array
        * param {array} [columns] List of columns to sort
        * param {array} [order_by] List of directions (ASC, DESC)
        * returns {array}
        */
            multisort: function (arr, columns, order_by) {
                if (typeof columns == 'undefined') {
                    columns = []
                    for (var x = 0; x < arr[0].length; x++) {
                        columns.push(x);
                    }
                }

                if (typeof order_by == 'undefined') {
                    order_by = []
                    for (var x = 0; x < arr[0].length; x++) {
                        order_by.push('ASC');
                    }
                }

                function multisort_recursive(a, b, columns, order_by, index) {
                    var direction = order_by[index] == 'DESC' ? 1 : 0;

                    var is_numeric = !isNaN(+a[columns[index]] - +b[columns[index]]);

                    var x = is_numeric ? +a[columns[index]] : a[columns[index]].toLowerCase();
                    var y = is_numeric ? +b[columns[index]] : b[columns[index]].toLowerCase();

                    if (x < y) {
                        return direction == 0 ? -1 : 1;
                    }

                    if (x == y) {
                        return columns.length - 1 > index ? multisort_recursive(a, b, columns, order_by, index + 1) : 0;
                    }

                    return direction == 0 ? 1 : -1;
                }

                return arr.sort(function (a, b) {
                    return multisort_recursive(a, b, columns, order_by, 0);
                });
            },
            sortby: function (arr, prop, reverse, numeric) {
                // Ensure there's a property
                if (!prop || !arr) {
                    return arr
                }

                // Set up sort function
                var sort_by = function (field, rev, primer) {

                    // Return the required a,b function
                    return function (a, b) {

                        // Reset a, b to the field
                        a = primer(a[field]), b = primer(b[field]);

                        // Do actual sorting, reverse as needed
                        return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * (rev ? -1 : 1);
                    }

                }

                if (numeric) {
                    // Do sort "in place" with sort_by function
                    arr.sort(sort_by(prop, reverse, function (a) {

                        // - Force value to a string.
                        // - Replace any non numeric characters.
                        // - Parse as float to allow 0.02 values.
                        return parseFloat(String(a).replace(/[^0-9.-]+/g, ''));

                    }));
                } else {

                    // Do sort "in place" with sort_by function
                    arr.sort(sort_by(prop, reverse, function (a) {

                        // - Force value to string.
                        return String(a).toUpperCase();

                    }));
                }
            }
        }

        $scope.sortData = function () {
            $scope.sortDesc = !$scope.sortDesc;

            switch ($scope.tableDisplay) {
                case "byCountyName":
                    if (!$scope.sortDesc)
                        sort.arr.multisort($scope.data, ['name', 'marketId'], ['ASC', 'ASC']);
                    else
                        sort.arr.multisort($scope.data, ['name', 'marketId'], ['DESC', 'DESC']);
                    break;
                case "byState":
                    if (!$scope.sortDesc)
                        sort.arr.multisort($scope.data, ['statePostalCode', 'name'], ['ASC', 'ASC']);
                    else
                        sort.arr.multisort($scope.data, ['statePostalCode', 'name'], ['DESC', 'DESC']);
                    break;
                case "byMarketNumber":
                    if (!$scope.sortDesc)
                        sort.arr.multisort($scope.data, ['marketId', 'marketName'], ['ASC', 'ASC']);
                    else
                        sort.arr.multisort($scope.data, ['marketId', 'marketName'], ['DESC', 'DESC']);
                    break;
                case "byMarketName":
                    sort.arr.sortby($scope.data, 'marketName', $scope.sortDesc, false);
                    break;
                case "byDistrict":
                    if (!$scope.sortDesc)
                        sort.arr.multisort($scope.data, ['district', 'name'], ['ASC', 'ASC']);
                    else
                        sort.arr.multisort($scope.data, ['district', 'name'], ['DESC', 'DESC']);

                    break;
            }


        }

        $scope.printView = function () {
			if ($scope.criteriaEntered() == false) {
				var noCriteriaMsg = Dialogger.alert('Print view is not available for an "all markets" search. <br />To print, you must enter at least one search criteria.');					
				return;
			}

			var data = [
                $scope.criteria.name,
                ($scope.criteria.number == "" ? null : $scope.criteria.number),
				($scope.criteria.district > 12 ? null : $scope.criteria.district),
                $scope.criteria.state ? $scope.criteria.state.fipsId : null,
                $scope.criteria.county ? $scope.criteria.county.countyId : null,
                $scope.criteria.city ? $scope.criteria.city.name : null,
                $scope.criteria.zip,
                $scope.tableDisplay,
                !$scope.sortDesc,
                $scope.data.length,
                $scope.countiesCount
            ];
            var reportType = 'marketsearch';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');

		}
    }
})();





;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('AdvMarketsService', AdvMarketsService);

    AdvMarketsService.$inject = ['$http', '$log', '$uibModal', 'toastr', '$state', 'StatesService'];

    function AdvMarketsService($http, $log, $uibModal, toastr, $state, StatesService) {
        var service = {
            AddCustomMarket: AddCustomMarket,
            getMemoHistory: getMemoHistory,
            AddCustomMarketPart: AddCustomMarketPart,
            AddCustomMarketParts: AddCustomMarketParts,
            AddCustomMarketCountyParts: addCustomMarketCountyParts,
            DeleteCustomMarketPart: DeleteCustomMarketPart,
            DeleteCustomMarketCounty: DeleteCustomMarketCounty,
            deleteCustomMarket: DeleteCustomMarket,
            checkStateBranches: checkStateBranches,
            getMarketsByState: getMarketsByState,
            getMarketsByStateAndDistrict: getMarketsByStateAndDistrict,
            getMarketsByStateAndCounty: getMarketsByStateAndCounty,
            getMarketsByStateAndMarketNo: getMarketsByStateAndMarketNo,
            getMarketsSearchData: getMarketsSearchData,
            getMarketById: getDefinition,
            getMarketByIdAdv: getDefinitionAdv,
            getMarketHhiById: getHhi,
            getMarketMapById: getMap,
            getMarketHistoryById: getHistory,
            getMarketPendingById: getPending,
            getPendingCount: getPendingCount,
            postAddEditMarketDefinition: postAddEditMarket,
            GetCustomMarkets: GetCustomMarkets,
            GetCustomMarketById: GetCustomMarketById,
            GetCustomMarketContentsLabel: GetCustomMarketContentsLabel,
            getProformaHHI: getProformaHHI,
            validateProformaHHI: validateProformaHHI,
            recalculateProformaHHI: recalculateProformaHHI,
            gatherMSA: gatherMSA,
            gatherNONMSA: gatherNONMSA,
            addOrEditMarket: addOrEditMarket,
            UpdateCustomMarket: UpdateCustomMarket,
            getMarketNumber: getMarketNumber,
            getDeleteRecodeMarketCity: getDeleteCityMarket,
            getAddCityToMarketByState: getAddCityMarket,
            getCitiesByState: getCities,
            openAddCityToMarket: openAddCityToMarket,
            postcreateCity: postcreateCity,
            updateMarketCities: updateMarketCities,
            getCommonMarkets: getCommonMarkets,
            getCreditUnionsForHHI: getCreditUnionsForHHI,
            getCreditUnionCountForHHI: getCreditUnionCountForHHI,
            checkIfUsingArchive: checkIfUsingArchive,
            getLastArchiveHistoryDate: getLastArchiveHistoryDate,
            getDivestAmount: getDivestAmount,
            getThriftWeightFootnote: getThriftWeightFootnote,
            getMultpleMarkets: getMultpleMarkets,
            hasCUNonCUPurchase: hasCUNonCUPurchase,
            getNumBranchesOverDepositAmt: getNumBranchesOverDepositAmt,
            getRssdsWithBranchesOverDepositAmt: getRssdsWithBranchesOverDepositAmt
        };

        return service;
        ////////////////

        function openAddCityToMarket(stateId, countyId, cityName) {
            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                templateUrl: 'AppJs/advanced/markets/views/_addCityToMarket.html',
                controller: ['$scope', '$uibModalInstance', 'StatesService', 'toastr', function ($scope, $uibModalInstance, StatesService, toastr) {
                    $scope.statesLoaded = false;
                    $scope.processing = false;
                    $scope.states = [];
                    $scope.cities = [];
                    $scope.city = null;
                    $scope.criteria = {
                        state: null,
                        county: null,
                        marketNum: null
                    };

                    activate();

                    function activate() {
                        StatesService.statesPromise.then(function (result) {
                            $scope.states = result;

                            $scope.criteria.state = _.find($scope.states, { stateId: stateId });
                            $scope.criteria.county = countyId != null ? _.find($scope.criteria.state.counties, { countyId: countyId }) : null;
                            $scope.criteria.city = cityName;


                            $scope.statesLoaded = true;

                            StatesService
                                .getCitiesOnly(stateId)
                                .then(function (data) {
                                    $scope.cities = data;
                                });

                        });
                    }

                    $scope.checkIfCityKnown = function () {
                        if ($scope.criteria.city != null &&
                            $scope.criteria.state != null &&
                            $scope.criteria.county != null)
                            StatesService
                                .getSingleCity({
                                    cityName: $scope.criteria.city,
                                    stateFipsId: $scope.criteria.state.stateId,
                                    countyId: $scope.criteria.county.countyId
                                }).then(function (data) {
                                    $scope.city = data;
                                });
                        else
                            $scope.city = null;
                    };

                    $scope.SaveCityMarket = function () {

                        $scope.processing = true;

                        //adding city
                        if ($scope.city == null) {
                            var dataCity =
                            {
                                cityName: $scope.criteria.city,
                                stateFipsId: $scope.criteria.state.stateId,
                                countyId: $scope.criteria.county.countyId
                            };

                            postcreateCity(dataCity)
                                .then(function (returnCityObj) {
                                    $uibModalInstance
                                        .close({
                                            scope: $scope.$root,
                                            cityId: returnCityObj.cityId,
                                            marketId: $scope.criteria.marketNum,
                                            stateId: $scope.criteria.state.stateId
                                        });
                                });
                        } else {
                            $uibModalInstance
                                .close({
                                    scope: $scope.$root,
                                    cityId: $scope.city.cityId,
                                    marketId: $scope.criteria.marketNum,
                                    stateId: $scope.criteria.state.stateId
                                });
                        }

                    };
                    $scope.Cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };

                }]
            }).result.then(function (result) {

                getAddCityMarket(result)
                    .then(function (data) {
                        $scope.processing = false;
                        if (data.recNotSaved == false) {
                            toastr.success("City added to Market sucessfully!");
                            result.scope.$broadcast('new-city-added', data);
                        }
                        else
                            toastr.error("Error adding City to Market.", data.errorMessage || "Please try again or contact support. Sorry about that.");
                        result.scope.$broadcast('new-city-added', data);
                    }, function (err) {
                        alert("Sorry. There was an error.");
                        result.scope.$broadcast('new-city-added', data);
                    });

            });
        };


        function postcreateCity(data) {

            return $http.post('api/admin/createCity', data)
                .then(function Success(result) {
                    return result.data;
                },
                    function Failure(result) {
                        toastr.error("Error creating new City.", data.errorMessage || "Please try again or contact support. Sorry about that.");
                        $log.error("Error creating new city", result);
                    });
        }

        function getMarketNumber(cityID) {
            return $http.get('/api/advmarkets/getMarketNumber', { params: { cityID: cityID } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning Market Number", result);
                });
        }

        function checkIfUsingArchive() {
            return $http.get('/api/advmarkets/CheckIfUsingArchive')
                .then(function Success(result) {
                    return result.data == 1 ? true : false;
                }, function Failure(result) {
                    $log.error("Error getting archive info", result);
                    return false;
                });
        }


        function getLastArchiveHistoryDate() {
            return $http.get('/api/history/structure-last-change-date-string')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting archive info", result);
                    return "";
                });
        }



        function addOrEditMarket(market, mode) {
            var marketID = 0;

            if (market != null) {
                marketID = market.definition.marketId;
                $state.params.marketId = marketID;
                //$scope.marketId = marketID;

            }

            $uibModal.open({
                animation: true,
                modal: true,
                size: 'lg',
                keyboard: false,
                backdrop: 'static',
                templateUrl: 'AppJs/advanced/markets/views/_addMarket.html',
                controller: 'advEditMarketController',
                resolve: {
                    marketID: function () {
                        return marketID;
                    }
                }
            })
                .result.then(function (result) {
                    postTophold(marketID, result)
                        .then(function (data) {

                            if (!data.errorFlag)
                                toastr.success(marketID ? "Market Definition was updated" : "Market Definition was added");
                            else {
                                var errorMessage = [];
                                if (data.messageTextItems.length > 0) {
                                    for (var i = 0; i < data.messageTextItems.length; i++) {
                                        errorMessage.push(data.messageTextItems[i]);
                                    }
                                }
                                toastr.error("There was an unexpected error.", errorMessage.join() || "Please try again or contact support. Sorry about that.");
                            }


                        }, function (err) {
                            alert("Sorry. There was an error.");
                        });

                }, function () {
                    //dismissed
                });
        }

        function getMarketsByStateAndDistrict(stateId, districtNo) {
            return $http.get('/api/advmarkets/state-and-district', { params: { stateId: stateId, districtNumber: districtNo } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning state-and-district data", result);
                });
        }

        function getMarketsByStateAndCounty(stateId) {
            return $http.get('/api/advmarkets/state-by-county', { params: { stateId: stateId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning state-by-county data", result);
                });
        }

        function getMarketsByStateAndMarketNo(stateId) {
            return $http.get('/api/advmarkets/state-by-marketnum', { params: { stateId: stateId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning state-by-marketnum data", result);
                });
        }


        function getMarketsSearchData(data) {
            return $http.get('/api/advmarkets/search', { params: { marketName: data.marketName, marketNumber: data.marketNumber, districtId: data.districtId, stateId: data.stateId, countyId: data.countyId, cityName: data.cityName, zip: data.zip } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market search data", result);
                });
        }

        function getDefinition(data) {
            return $http.get('/api/advmarkets/marketById', { params: { marketId: data.marketId, getDefinition: data.getDefinition } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market definition data", result);
                });
        }
        function getDefinitionAdv(data) {
            return $http.get('/api/advmarkets/marketByIdAdv', { params: { marketId: data.marketId, getDefinition: data.getDefinition, getPending: data.getPending } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market definition data", result);
                });
        }
        function getHhi(data) {
            return $http.get('/api/advmarkets/marketById', { params: { marketId: data.marketId, getHhi: data.getHhi } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market Hhi data", result);
                });
        }

        function getMap(data) {
            return $http.get('/api/advmarkets/marketById', { params: { marketId: data.marketId, getMap: data.getMap } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market map data", result);
                });
        }

        function getMultpleMarkets(marketIds) {

            return $http.post('/api/advMarkets/get-markets-by-ids', marketIds)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market map data", result);
                });
        }

        function getHistory(data) {
            return $http.get('/api/advmarkets/marketById', { params: { marketId: data.marketId, getHistory: data.getHistory, getDefinition: true } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market history data", result);
                });
        }

        function getMemoHistory(marketHistoryMemoId) {

            return $http.get('/api/advmarkets/market-history-memo', { params: { marketHistoryMemoId: marketHistoryMemoId } })
                .then(function Success(result) {
                    //$log.info("sucess" + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning get History Memo Transaction", result);
                });
        }

        function getPending(data) {
            return $http.get('/api/pending/GetPending', { params: { marketId: data.marketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market pending data", result);
                });
        }

        function getPendingCount(data) {
            return $http.get('/api/pending/GetPendingCount', { params: { marketId: data } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning pending count", result);
                });
        }

        function postAddEditMarket(data) {
            return $http.post('/api/advmarkets/AddEditMarket', data)
                .then(function Success(result) {
                    return result;
                }, function Failure(result) {
                    $log.error("Error updating market data", result);
                });
        }

        //
        function GetCustomMarkets() {
            return $http.get('/api/advmarkets/get-custom-markets')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting custom market data", result);
                });
        }


        function GetCustomMarketById(marketId) {
            return $http.get('/api/advmarkets/get-custom-market-byid', { params: { customMarketID: marketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting custom market data by Id", result);
                });
        }

        function GetCustomMarketContentsLabel(marketId) {
            return $http.get('/api/advmarkets/get-custom-market-content-label', { params: { customMarketID: marketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting custom market report label", result);
                });
        }

        function AddCustomMarket(name) {
            return $http.get('/api/advmarkets/add-custom-market', { params: { name: name } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error adding custom market data", result);
                });
        }

        function UpdateCustomMarket(data) {
            return $http.post('/api/advmarkets/update-custom-market', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error updating custom market data", result);
                });
        }
        function DeleteCustomMarketCounty(data) {
            return $http.post('/api/advmarkets/del-custom-market-county', data, { params: { countyId: data.countyId, customMarketId: data.customMarketId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error deleting custom market parts data", result);
                });
        }
        function DeleteCustomMarketPart(data) {
            return $http.post('/api/advmarkets/del-custom-market-part', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error deleting custom market parts data", result);
                });
        }
        function DeleteCustomMarket(customMarketID) {
            return $http.get('/api/advmarkets/deleteCustomMarket', { params: { customMarketID: customMarketID } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error deleting custom market data", result);
                });
        }
        function AddCustomMarketPart(data) {
            return $http.post('/api/advmarkets/addCustomMarketPart', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error adding custom market parts data", result);
                });
        }
        function AddCustomMarketParts(data) {
            return $http.post('/api/advmarkets/addCustomMarketParts', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error adding custom market parts data", result);
                });
        }

        function addCustomMarketCountyParts(data) {
            return $http.post('/api/advmarkets/addCustomMarketCountyParts', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error adding custom market county parts data", result);
                });
        }

        function checkStateBranches(stateFipsId) {
            return $http.get('/api/advmarkets/checkStateBranches', { params: { stateFipsId: stateFipsId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting state branches data", result);
                });
        }
        function validateProformaHHI(data) {
            //return $http.get('/api/advmarkets/get-ProformHHI', { params: { marketID: data.marketID, msaId: data.msaId, customMarket: data.customMarket, buyer: data.buyer, targets: data.targets } })
            return $http.post('/api/advmarkets/validate-proformhhi', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error gathering Proform", result);
                });
        }

        function getProformaHHI(data) {
            //return $http.get('/api/advmarkets/get-ProformHHI', { params: { marketID: data.marketID, msaId: data.msaId, customMarket: data.customMarket, buyer: data.buyer, targets: data.targets } })
            return $http.post('/api/advmarkets/get-proformhhi', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error gathering Proform", result);
                });
        }

        function getThriftWeightFootnote(weightRuleId) {
            return $http.get('/api/advmarkets/get-thriftWeightNote', { params: { weightRuleId: weightRuleId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting thrift weight footnote", result);
                });
        }

        function getCreditUnionsForHHI(data) {
            return $http.post('/api/advmarkets/creditunionsummaries-by-market', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error finding credit unions", result);
                });
        }

        function getCreditUnionCountForHHI(data) {
            return $http.post('/api/advmarkets/creditunion-count-by-market', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting credit union count", result);
                });
        }


        function recalculateProformaHHI(data) {
            return $http.post('/api/advmarkets/recalculate-ProformHHI', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error recalculating HHI", result);
                });
        }

        function gatherMSA() {
            return $http.get('/api/advmarkets/gathermsa')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error gather MSA List", result);
                });
        }
        function gatherNONMSA() {
            return $http.get('/api/advmarkets/gathernonmsa')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error gather NON-MSA List", result);
                });
        }
        function getMarketsByState(stateId) {
            return $http.get('/api/advmarkets/recode-market', { params: { stateId: stateId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning Recode Market data", result);
                });
        }

        function updateMarketCities(marketCities) {
            return $http.post('/api/advmarkets/update-market-cities', marketCities)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error updating Recode Market data", result);
                });
        }

        function getDeleteCityMarket(cityId, stateId) {
            return $http.get('/api/advmarkets/city-recode-market-delete', { params: { cityId: cityId.cityId, stateId: cityId.stateId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning Deleting Recode Market data", result);
                });
        }


        function getAddCityMarket(data) {
            return $http.get('/api/advmarkets/add-city-market', { params: { marketId: data.marketId, cityId: data.cityId, stateId: data.stateId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning adding City to Recode Market data", result.data);
                });
        }

        function getCities(stateId) {
            return $http.get('/api/advmarkets/get-cities', { params: { stateId: stateId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning city for Market data", result);
                });
        }

        function getCommonMarkets(buyer, targets, branches, removedTargets, treatSLHCBuyerAsBHC) {
            return $http.get('/api/analysis/get-common-markets', { params: { buyer: buyer, targets: targets, branches: branches, removedTargets: removedTargets, treatSLHCBuyerAsBHC: treatSLHCBuyerAsBHC } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning common markets data", result);
                });
        }

        //function getAllCommonStates(buyer, targets, branches) {
        //    return $http.get('/api/analysis/get-common-states', { params: { buyer: buyer, targetRssds: targets, branches: branches } })
        //        .then(function Success(result) {
        //            return result.data;
        //        }, function Failure(result) {
        //            $log.error("Error returning common markets data", result);
        //        });
        //}

        //int marketId,long buyerRssdId, long[] targetRssdIds, int divToOrgTypeId
        function getDivestAmount(marketId, buyerRssd, targetBranchIds, targetRssds, divestToOrgTypeId, banksOnly) {
            var data = { MarketId: marketId, BuyerRSSDId: buyerRssd, TargetBranchIds: targetBranchIds, TargetRSSDIds: targetRssds, DivestToType: divestToOrgTypeId, OnlyBanksInCalcs: banksOnly };

            return $http.post('/api/AdvMarkets/divest-amount', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning divestiture amount.", result);
                });
        }

        function hasCUNonCUPurchase(marketId) {
            return $http.get('/api/AdvMarkets/hasCUNonCUPurchase', { params: { marketId: marketId} })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error searching for Credit Union purchase of bank/thrift.", result);
                });
        }

        function getNumBranchesOverDepositAmt(data) {
            return $http.post('/api/AdvMarkets/NumBranchesWithDepositsOverAmt', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting branch count for deposit level.", result);
                });
        }

        function getNumListBranchesOverDepositAmt(depositAmt, branchIds) {
            return $http.get('/api/advmarkets/add-city-market', { params: { depositAmt: depositAmt, branchIds: branchIds } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting count of branches over deposit amount.", result.data);
                });
        }

        function getRssdsWithBranchesOverDepositAmt(data) {
            return $http.post('/api/AdvMarkets/InstRssdWithBillionDollarBranches', data)
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error getting RSSDs for branch with deposit level.", result);
                });
        }
    }
})();

;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('advCommonMarketsController', advCommonMarketsController);

    advCommonMarketsController.$inject = ['$scope', '$stateParams', 'AdvMarketsService', 'AdvInstitutionsService', 'UserData', '$state', '$window', 'toastr', '$uibModal'];

    function advCommonMarketsController($scope, $stateParams, AdvMarketsService, AdvInstitutionsService, UserData, $state, $window, toastr, $uibModal) {
        angular.extend($scope, {
            data: [],
            dataReady: false,
            criteria: [],
            hasInvalidParams: false,
            branches:[],
            marketIds: [],
            rssidList: [],
            survivorClass: null,
            nonSurvivorClass: null,
            searchData: false,
            shlcBHC: false,
            survivorNoActive: false,
            nonSurvivorNoActive: false,
            nonSurvivorNoActiveRssdIds: null,
            nonSurvivorNoActiveTitle: null,
            bankToTopHold: false,
            bankToTopHoldTitle: null,
            selectedBranches: [],
            selectedInst: [],
            instRssdIdWithBranches: null,
            removedTargets: [],
            marketBranches: [],
            topHoldToBranch: false,
            sameRssdId: false,
            sameOrg: false,
            sameOrgRssdId: null,
            institutions: [],
            activationComplete: false
        });
        $scope.todaysDate = new Date();
        $scope.UserData = UserData;
        $scope.selectAll = false;
        $scope.selectAllExceeds = false;
        $scope.buyer = $scope.criteria.buyer;
        $scope.bhcOrthc = null;
        $scope.targets = $scope.criteria.targets;

        $scope.verifyNonSurvivor = function () {
            var targetIds = [];
            var match = false;
            var rssdid = null;
            if ($scope.criteria.buyer == null) { return; }
            
            if (_.indexOf($scope.criteria.targets, ",") > - 1) {
                targetIds = $scope.criteria.targets.split(",");

                for (var i = 0; i < targetIds.length; i++) {
                    var tg = targetIds[i].trim();
                    if (tg == $scope.criteria.buyer) {
                        rssdid = tg;
                        match = true;
                        break;
                    }
                }

            }
            else {

                if ($scope.criteria.targets == $scope.criteria.buyer) {
                    rssdid = $scope.criteria.targets;
                    $scope.criteria.targets = null;
                    match = true;
                }
            }
            if (!match) {

                if (_.indexOf($scope.removedTargets, ",") > -1) {
                    var found = _.find($scope.removedTargets, $scope.criteria.buyer);
                    if (found) {
                        match = true;
                    }
                }
                else {
                    if ($scope.criteria.buyer == $scope.removedTargets) {
                        match = true;
                    }
                }
            }

            if (match) {
                $scope.sameRssdId = true;
                $scope.searchData = false;
            }
            else {
                $scope.sameRssdId = false;
                $scope.getInstitutionInfo();

            }

            return match;

        }
        $scope.selectOverlapExceed = function () {
           // $('chkselectAll').attr('checked', false);
            document.getElementById("chkselectOverlaping").checked = false;
            if (document.getElementById("chkselectAllExceeds").checked) { $scope.marketIds = [];}
            for (var i = 0; i < $scope.data.markets.length; i++) {
                
                if ($scope.data.markets[i].exceedsAuthority) {
                    var marketId = $scope.data.markets[i].market.marketId;
                    $scope.addedMarket(marketId);

                }

            }
           
        }
        $scope.getMarket = function () {
            $scope.nonSurvivorNoActiveRssdIds = null;
            $scope.targets = $scope.criteria.targets;
            $scope.buyer = $scope.criteria.buyer;
            $scope.searchData = true;

            if ($scope.criteria.targets != "")
                 $scope.checkIsActiveBuyer();
 

            if ($scope.targets != "" || $scope.removedTargets) {
                var data = { targetRSSDId: ($scope.criteria.targets == "" ? $scope.removedTargets: $scope.criteria.targets) }
                AdvInstitutionsService
                 .isActiveRSSDId(data)
                 .then(function (result) {
                     if (result) {
                         $scope.nonSurvivorNoActiveRssdIds = _.filter(result, ["isActive", false]);
                         if ($scope.nonSurvivorNoActiveRssdIds.length > 0) {
                             $scope.nonSurvivorNoActive = true;
                             $scope.nonSurvivorNoActiveTitle = _.join(_.flatMap($scope.nonSurvivorNoActiveRssdIds, "rssdId"), ", ");
                             $scope.searchData = false;
                         }
                         else {
                             $scope.nonSurvivorNoActive = false;
                             $scope.verifyNonSurvivor();
                         }
                     }
                 });

            }
            else {
                if ($scope.branches != null) {
                    $scope.getInstitutionInfo();
                }
            }


        }
        $scope.checkIsActiveBuyer = function () {
            var data = { targetRSSDId: $scope.criteria.buyer }
            AdvInstitutionsService
              .isActiveRSSDId(data)
               .then(function (result) {
                   var org = result;
                   if (org[0].isActive) {
                       $scope.survivorNoActive = false;
                       if ($scope.targets == null) {
                           $state.go('root.adv.institutions.summary.markets', { rssd: $scope.criteria.buyer });
                       }
                   }
                   else {
                       $scope.survivorNoActive = true;
                       $scope.searchData = false;
                   }
            });

        };
        $scope.addedMarket = function (marketId) {
            if (_.indexOf($scope.marketIds, marketId) > -1) { // is currently selected
                var idx = _.indexOf($scope.marketIds, marketId);
                $scope.marketIds.splice(idx, 1);
            } else { // is newly selected
                $scope.marketIds.push(marketId);
            }
        };
        $scope.selectOverlap = function () {
            //  $('chkselectAllExceeds').attr('checked', false);
            document.getElementById("chkselectAllExceeds").checked = false;
            if (document.getElementById("chkselectOverlaping").checked) { $scope.marketIds = []; }
            for (var i = 0; i < $scope.data.markets.length; i++) {
                // if (!$scope.data.markets[i].exceedsAuthority) {
                var marketId = $scope.data.markets[i].market.marketId;
                $scope.addedMarket(marketId);

                // }
            }
        };
        $scope.saveMarketsToSession = function () {

            for (var i = 0; i < $scope.data.markets.length; i++) {
                var marketId = $scope.data.markets[i].market.marketId;
                var idx  = _.indexOf($scope.marketIds, marketId);
                if (idx > -1) {
                    var mrk = { marketId: marketId, marketName: $scope.data.markets[i].market.name };
                    UserData.markets.save(mrk);
                }

            }

        };
        $scope.runProFormaSelectedMarkets = function () {
            var buyer = $scope.buyer;
            var targets = $scope.targets;
            var marketNum = $scope.marketIds;

            
            //$window.open('/report/commonmarketproformapdf?markets=' + marketNum + '&buyer=' + buyer + '&target=' + targets + '&branches=' + $scope.branches, '_blank');  
            $window.open('/report/commonmarketadvancedproformapdf?markets=' + marketNum + '&buyer=' + buyer + '&target=' + targets + '&branches=' + $scope.branches + '&shlcBHC=' + $scope.shlcBHC, '_blank');
            
            toastr.success("Report generated and ran in a new window.");
        };
        $scope.printView = function () {
            var buyer = $scope.buyer;
            var targets = $scope.criteria.targets;
            var branches = ($scope.branches.length == 0 ? "": $scope.branches);
            var removedTargets = ($scope.removedTargets.length == 0 ? "" : $scope.removedTargets);
            $window.open('/report/CommonMarketsReportAdv?buyer=' + buyer + '&targets=' + targets + '&branches=' + branches + '&removedTargets=' + removedTargets + '&shlcBHC=' + $scope.shlcBHC, '_blank');
            toastr.success("Report generated and ran in a new window.");

        };
        $scope.backToForm = function () {
            $scope.data = null;
            $scope.dataReady = false;
            $scope.buyer = null;
            $scope.criteria.buyer = null;
            $scope.targets = null;
            $scope.criteria.targets = null;
            $scope.marketIds = [];
            $scope.institutions = [];
            $scope.selectedInst = [];
            $scope.branches = [];
        };
        $scope.getInstitutionInfo = function () {
            AdvInstitutionsService
            .getInstitutionData({ rssdId: $scope.criteria.buyer, getDetail: true, getBranches: true, getOperatingMarkets: false, getHistory: false })
            .then(function (result) {
                if (result && result != null) {
                    $scope.survivorDefinition = result.definition;
                    $scope.survivorClass = $scope.survivorDefinition.class;
                    if ($scope.survivorClass == "SLHC") {    
                        var data = { targetRSSDId: $scope.criteria.targets }
                        AdvInstitutionsService
                         .hasBankOrBHC(data)
                         .then(function (result) {
                             if (result) {
                                 $scope.searchData = false;
                                 $uibModal.open({
                                     animation: true,
                                     modal: true,
                                     backdrop: false,
                                     size: 'lg',
                                     templateUrl: 'AppJs/advanced/markets/views/analysis/_slhc.html',
                                     controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
                                         $scope.select = function (value) {
                                             $uibModalInstance.close(value);
                                         };
                                         $scope.cancel = function () {
                                             $uibModalInstance.close('cancel');
                                         };
                                     }]
                                 }).result.then(function (result) {
                                     $scope.bhcOrthc = result;
                                     if ($scope.bhcOrthc == "cancel") {

                                         return;
                                     }
                                     if ($scope.bhcOrthc == "SLHC") {

                                         $scope.getCommonMarkets(false);
                                     }
                                     else
                                         $scope.getCommonMarkets(true);
                                 });
                             }
                             else {
                                 $scope.getCommonMarkets(true);
                             }
                         });

                    }
                    else {
                        $scope.getCommonMarkets(true);
                    }
                }

            });

        };
        $scope.isSavedInst = function () {
            var inst = _.cloneDeep(UserData.institutions.get());

            if (inst.length > 0)
                return false;
            else
                return true;
        };

        $scope.getCommonMarkets = function (treatSLHCBuyerAsBHC) {
            $scope.searchData = true;
            $scope.shlcBHC = treatSLHCBuyerAsBHC;
           // $scope.cleanTargets();
            AdvMarketsService
                .getCommonMarkets($scope.criteria.buyer, $scope.criteria.targets == null ? "" : $scope.criteria.targets, $scope.branches.length == 0 ? "" : $scope.branches, $scope.removedTargets.length == 0 ? "" : $scope.removedTargets, treatSLHCBuyerAsBHC)
                .then(function (result) {
                    var srvResult = result.serviceResultMsg;
                    if (!srvResult.errorFlag) {
                        $scope.data = result;
                        $scope.dataReady = true;
                        if (!result.commonStates.errorFlag)
                            $scope.commonStates = result.commonStates.resultObject;
                        else
                            toastr.error($scope.commonStates.messageTextItems[0]);                            
                        $scope.searchData = false;
                        $scope.bankToTopHold = false;
                        $scope.topHoldToBranch = false;
                    }
                    else {
                        if (srvResult.messageTextItems[0].indexOf("A holding company")  > -1)
                        {
                            $scope.topHoldToBranch = true;
                        }
                        if (srvResult.messageTextItems[0].indexOf("ValidateError") > -1) {
                            $scope.sameOrg = true;
                            $scope.sameOrgRssdId = srvResult.messageTextItems[0].replace("ValidateError", "");
                        }
                        else {
                            $scope.bankToTopHold = true;                       
                            $scope.bankToTopHoldTitle = srvResult.messageTextItems[0];
                        }
                        $scope.searchData = false;
                    }
                });
        }
        $scope.cleanTargets = function () {
            var currentTargets = [];

            if ($scope.criteria.targets.indexOf(",") > -1){
                currentTargets = $scope.criteria.targets.split(",");

            }
            else {
                $scope.criteria.targets = null;;
            }

            for (var i = 0; i < $scope.selectedInst.length; i++) {
                if (_.find(currentTargets, $scope.selectedInst[i])) {
                    var stInst = $scope.selectedInst[i]
                    var idx = _.indexOf(currentTargets, stInst);
                    if (idx > -1)
                        currentTargets.splice(idx, 1);

                }
            }

            $scope.criteria.targets = _.join(_.flatMap(currentTargets), ",");
            $scope.removedTargets =  _.join(_.flatMap($scope.selectedInst), ",");
        }
           
        $scope.loadInstBranchPicker = function (buyer, mainInstitutions) {
            $uibModal.open({
                size: 'lg',
                backdrop: 'static',
                keyboard: false,
                templateUrl: 'Appjs/advanced/markets/views/analysis/_InstitutionBranchPicker.html',
                controller: ["$uibModalInstance", "$scope", "UserData", "AdvInstitutionsService", "$timeout", "$state", function ($uibModalInstance, $scope, UserData, AdvInstitutionsService, $timeout, $state) {
           
                    $scope.selectedBranches = [];
                    $scope.selectedInstitutions = [];
                    $scope.institutions = [];
                    $scope.newRssdId = null;
                    $scope.isTopHold = false;
                    $scope.loaded = false;
                    $scope.class = null;
                    $scope.buyer = buyer;
                    activate();

                    function activate() {

                        AdvInstitutionsService
                       .getInstitutionData({ rssdId: buyer, getDetail: true, getBranches: false, getOperatingMarkets: false, getHistory: false })
                        .then(function (result) {
                            if (result) {
                                var def = result.definition;
                                $scope.class = def.class;
                                if (def.orgType == "Tophold") {
                                    $scope.isTopHold = true;
                                }
                            }
                            $scope.insts = _.cloneDeep(UserData.institutions.get());
                            
                            for (var i = 0; i < mainInstitutions.length; i++) {
                                $scope.addedInstitution(mainInstitutions[i]);
                                if (mainInstitutions[i].branches.length > 0) {
                                    for (var x = 0; x < mainInstitutions[i].branches.length; x++) {
                                        $scope.addedBranch(mainInstitutions[i].branches[x], mainInstitutions[i]);
                                    }
                                }
                            }

                            $scope.removeBuyersTree();
                           $scope.loaded = true;
                        });
                    }
                    $scope.removeBuyersTree = function () {
                        var removed = false;
                        // Tophold
                        if (_.indexOf($scope.insts, { rssdId: buyer }) > -1) {
                            var idx = _.indexOf($scope.insts, { rssdId: buyer });
                            $scope.insts.splice(idx, 1);
                            removed = true;
                        }
                        if (!removed) {
                            for (var i = 0; i < $scope.insts.length; i++) {
                                for (var x = 0; x < $scope.insts[i].orgs.length; x++) {
                                    if ($scope.insts[i].orgs[x].rssdId == buyer){
                                        $scope.insts.splice(i, 1);
                                        break;
                                    }
                                }

                            }
                        }
                    };
                    $scope.cancel = function () {
                        $uibModalInstance.close('cancel');
                    };
                    $scope.addedInstitution = function (inst) {

                        var foundInst = _.find($scope.institutions, { rssdId: inst.rssdId });

                        if (foundInst) {
                            var idx = _.indexOf($scope.institutions, foundInst);
                            $scope.institutions.splice(idx, 1);
                            $scope.selectedInstitutions.splice(idx, 1);
                        } else { // is newly selected
                            var scopeInst = { rssdId: inst.rssdId, name: inst.name, city: inst.city, statecode: inst.statecode, parentId: inst.parentId, 'class': inst.class, branches: [] };
                            $scope.institutions.push(scopeInst);
                            $scope.selectedInstitutions.push(inst.rssdId);
                        }
                    };
                    $scope.saveSelection = function () {
                        $uibModalInstance.close($scope.institutions);
                    };
                    $scope.addedBranch = function (branch, inst) {

                        var foundInst = _.find($scope.institutions, { rssdId: inst.rssdId });

                       if (foundInst) {
                           var branches = foundInst.branches;
                           var count = 0;

                           for (var i = 0; i < branches.length; i++) {
                               if (branches[i].branchId == branch.branchId) {
                                   foundInst.branches.splice(i, 1);
                                   $scope.selectedBranches.splice(i, 1);
                                   count++;
                               }
                           }
                           if (count == 0) {
                               foundInst.branches.push(branch);
                               $scope.selectedBranches.push(branch.branchId);
                           }
                            
                        } else {
                            var instituion = { rssdId: inst.rssdId, name: inst.name, branches: [] };
                            instituion.branches.push(branch);
                            $scope.selectedBranches.push(branch.branchId);
                            $scope.institutions.push(instituion);
                            $scope.selectedInstitutions.push(instituion.rssdId);

                        }


                        
                    };
                }]
            }).result.then(function (result) {
                if (result == "cancel") {
                    $scope.searchData = false;
                }
                else
                {
                    $scope.institutions = [];
                    $scope.institutions = result;
                    if (result.length >= 0) {
                        var targets = [];
                        
                        var copyOfBranches = [];
                        var removedTargets = [];
                        var br = false;
                        var ct = 0;
                   
                        
                        for (var i = 0; i < result.length; i++) {
                            if (result[i].branches.length > 0) {                                                                             
                                if (result[i].branches.length > 0) {
                                    $scope.selectedInst.push(result[i].rssdId);
                                    removedTargets.push(result[i].rssdId);
                                    ct = ct + 1;
                                    for (var x = 0; x < result[i].branches.length; x++) {
                                        copyOfBranches.push(result[i].branches[x].branchId);
                                        $scope.selectedBranches.push(result[i].branches[x].branchId);
                                    }
                                }

                            }
                            else {
                                targets.push(result[i].rssdId);                               
                            }
                        }
                        for (var x = 0; x < targets.length; x++) {
                            for (var y = 0; y < $scope.institutions.length; y++) {
                                if ($scope.institutions[y].rssdId == targets[x]) {
                                    $scope.institutions.splice(y, 1);
                                }
                            }
                           
                        }
                        //var found = _.find(targets, { rssdId: inst.rssdId }); check the duplicate values
                        if (ct > 0) {
                            $scope.branches = _.join(_.flatMap(copyOfBranches), ",");
                           
                        }
                        $scope.criteria.targets = _.join(_.flatMap(targets), ",");
                        $scope.removedTargets = _.join(_.flatMap(removedTargets ), ",");
                    }
                }
            });

        };
        $scope.removeInst = function (inst) {

            if (_.indexOf($scope.selectedInst, inst.rssdId) > -1) {
                var x = _.indexOf($scope.selectedInst, inst.rssdId);
                $scope.selectedInst.splice(x, 1);
            }

            for (var i = 0; i < $scope.institutions.length; i++) {
                if ($scope.institutions[i].rssdId == inst.rssdId){
                    $scope.institutions.splice(i, 1);
                    break;
                }
            }

            $scope.criteria.targets = _.join(_.flatMap($scope.institutions, "rssdId"), ",");
        };
        $scope.removeBranch = function (branch, inst) {

            var branches = inst.branches;
            if(_.indexOf($scope.selectedBranches,branch.branchId) > -1){
                var st = _.indexOf($scope.selectedBranches,branch.branchId);
                $scope.selectedBranches.splice(st, 1);
            }

            if (_.indexOf(branches, branch) > -1) {
                var idx = _.indexOf(branches, branch);
                
                inst.branches.splice(idx, 1);
            }
            var copyOfBranches = [];

            for (var i = 0; i < $scope.institutions.length; i++) {
                if ($scope.institutions[i].branches.length > 0) {
                    for (var x = 0; x < $scope.institutions[i].branches.length; x++) {
                        copyOfBranches.push($scope.institutions[i].branches[x].branchId);
                    }

                }
            }

            if (copyOfBranches.length > 0) {
                $scope.branches = _.join(_.flatMap(copyOfBranches), ",");
            }
            else {
                $scope.branches = null;
            }

            if(inst.branches.length == 0) {
                $scope.removeInst(inst);
            }
        };


        activate();

        function activate() {

            window.scrollTo(0, 0);
            $scope.criteria.buyer = null;
            $scope.activationComplete = true;
        }

    }
})();;
(function ()
{
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketDetailMapController', AdvMarketDetailMapController);

    AdvMarketDetailMapController.$inject = ['$scope', '$state','$stateParams', 'AdvMarketsService', 'leafletData', 'leafletBoundsHelpers', 'MarketsService', 'AdvBranchesService', 'MarketMapService', 'toastr', '$timeout'];

	function AdvMarketDetailMapController($scope, $state, $stateParams, AdvMarketsService, leafletData, leafletBoundsHelpers, MarketsService, AdvBranchesService, MarketMapService, toastr, $timeout)
	{
		$scope.marketMap = null;
        var branchData = null;
        var allBranchData = null;
        $scope.markers = [];
        var year = (new Date()).getFullYear();
        var mapBoxAndOpenMapsAttribution = '&copy;' + year + ' <a href="https://www.mapbox.com/about/maps/">MapBox</a> &copy;' + year + ' <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>';
        var cssAdded = false;


		angular.extend($scope, {
			marketDisplayInfo: {},
            printMap: printMap,
            toggleMapFullScreen: toggleMapFullScreen,
            isMapShapeCurrent: true,
            leafletData: leafletData,
            mapReady: false,
            center: {},
            geoJson: {},
            layers: {
                overlays: {}
            },
            bounds: null,
            showBranches: false,
            toggleBranches: toggleBranches,
            showCounties: true, //affects map style
            showCities: true, //affects map style
            showRoads: true, //affects map style
            setMapStyle: setMapStyle,
            showMarket: true,
            toggleMarket: toggleMarket,
            showOtherMarkets: false,
            toggleOtherMarkets: toggleOtherMarkets,
            showStates: false,
            toggleStates: toggleStates,
            markers: {},
            hoveredMarket: null,
            marketUndefined: false,
            displayMapFullScreen: false,
            mapStyles: {
                "CountiesRoadsCities": {
                    name: 'Counties, Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdk0r3001uganjch20akrs',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: true
                    }
                },
                "Counties": {
                    name: 'Counties Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhoaj50020ganjjg9cvcxi',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: false
                    }
                },
                "Roads": {
                    name: 'Roads Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhlhll001wg7ncl1gps309',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: false
                    }
                },
                "Cities": {
                    name: 'Cities Only',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circdkdbp001gg8m4xzloqdl5',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: true
                    }
                },
                "CountiesRoads": {
                    name: 'Counties & Roads',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhsd0o001xg7nc6tkcbv4y',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: true,
                        cities: false
                    }
                },
                "RoadsCities": {
                    name: 'Roads & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circddako001tganj2eqgiaph',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: true,
                        cities: true
                    }
                },
                "CountiesCities": {
                    name: 'Counties & Cities',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'circhhjbj001igfkvz8hqfkxe',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: true,
                        roads: false,
                        cities: true
                    }
                },
                "None": {
                    name: 'None',
                    url: 'https://api.mapbox.com/styles/v1/adgsupport/{mapid}/tiles/256/{z}/{x}/{y}?access_token={apikey}',
                    options: {
                        apikey: 'pk.eyJ1IjoiYWRnc3VwcG9ydCIsImEiOiJjaXFrdjBiOHcwM2ZoZ2drdnpobDBsZjZsIn0.29aGrinwXjdXJyTI_vPB8A',
                        mapid: 'cirqcpxde002pg9nggrktu888',
                        attribution: mapBoxAndOpenMapsAttribution
                    },
                    type: 'xyz',
                    data: {
                        counties: false,
                        roads: false,
                        cities: false
                    }
                }
            }
            });



        function refreshMarkers() {
            if ($scope.showBranches) {
                callBranches();
        }
        };

        activate();


        function activate() {	
			
			$scope.$watch('marketLoaded', function (dataLoaded) {
                if (dataLoaded) {
                    populateMap();
                }
            });

            if (!cssAdded) {
                // load in the print css
                cssAdded = true;
                var cssTag = document.createElement("link");
                cssTag.type = "text/css";
                cssTag.rel = "stylesheet";
                cssTag.href = "/content/css/mapPrint.css";
                document.getElementsByTagName("head")[0].appendChild(cssTag);
            }
    }


        function populateMap() {

			$scope.$on("leafletDirectiveGeoJson.leafy.mouseout",
				function (ev, leafletPayload) {
					$scope.hoveredMarket = null;
				});

			$scope.$on('leafletDirectiveMap.leafy.dragend', function (event) {
				refreshMarkers();
			});

			$scope.$on('leafletDirectiveMap.leafy.zoomend', function (event) {
				refreshMarkers();
			});

			$scope.$on('leafletDirectiveMap.leafy.load', function (event) {
				addPrintClass();
			});

			$scope.$on("leafletDirectiveGeoJson.leafy.click", function (ev, leafletPayload) {
					var feature = leafletPayload.leafletObject.feature;
				$state.go("root.adv.markets.detail.definition", { market: feature.properties.marketId });
			});

			$scope.$on("leafletDirectiveGeoJson.leafy.mouseover",
				function (ev, leafletPayload) {

					var layer = leafletPayload.leafletEvent.target,
						feature = leafletPayload.leafletObject.feature;

					layer.setStyle({
						weight: 4,
						color: "#000",
						fillOpacity: 0.75
					});
					layer.bringToFront();

					$scope.hoveredMarket = feature.properties;
				});			

			setMapStyle();

            MarketsService.find($stateParams.market, { getMap: true })
                .then(function (marketMap) {

                    $scope.marketMap = marketMap.map;
                    $scope.marketUndefined = marketMap.map.geoJson == null;
					$scope.isMapShapeCurrent = marketMap.map.isMapShapeCurrent;

					$scope.marketDisplayInfo = { 'name': $scope.$parent.market.definition.name, 'description': $scope.$parent.market.definition.Description, 'marketId': $scope.$parent.market.definition.marketId };
					
                    var bounds = null;
                    if (marketMap.map.geoJson) {
                        bounds = leafletBoundsHelpers.createBoundsFromArray([
                            [marketMap.map.geoJson.bbox[1], marketMap.map.geoJson.bbox[0]],
                            [marketMap.map.geoJson.bbox[3], marketMap.map.geoJson.bbox[2]]
                        ]);
                        delete marketMap.map.geoJson.bbox;
                    }
                    $scope.bounds = bounds;
					$scope.center = {};

                    $scope.layers.overlays.market = {
                        name: "theMarket",
                        type: "geoJSONShape",
                        data: $scope.marketMap.geoJson,
                        layerOptions: {
                            style: {
                                //fillColor: result.map.color || "#577492",
                                fillColor: "blue",
                                weight: 2,
                                opacity: 1,
                                color: 'white',
                                dashArray: '3',
								fillOpacity: 0.2
							},
							onEachFeature: function (feature, layer) {
								layer.on('mouseover', function () {
									highlightViewedMarketMap(layer, true);							
								}); 
								layer.on('mouseout', function () {
									highlightViewedMarketMap(layer, false);
								})
							}
                        },
						visible: true,						
                        layerParams: {
                            showOnSelector: false
						}
                    };

                    leafletData.getMap()
                        .then(function (map) {
                            map.fitBounds(map.getBounds());
                        });

                    $scope.mapReady = true;                   
                });

		}

		function highlightViewedMarketMap(layer, showHighlight) {
			if (showHighlight) {
				$timeout(function () {
					$scope.hideMapMarketLink = true;
					$scope.hoveredMarket = $scope.marketDisplayInfo;
					layer.setStyle({
						weight: 3,
						color: "#595959",
						fillOpacity: 0.6,
						opacity: 1
					});
					layer.bringToFront();
				}, 0); // use timeout to avoid race condition with mouse outs from surrounding market shape layers
			}
			else {
				// no timeout here. On the mouse out we want it to happen asap so we don't mess with any other mouse over events..
				$scope.hideMapMarketLink = false;
				$scope.hoveredMarket = null;
				layer.setStyle({
						weight: 2,
						color: "white",
						fillOpacity: 0.25
					});   
			}
		}

        function printMap() {
            window.print();
        }

        function toggleMapFullScreen() {
            $scope.displayMapFullScreen = !$scope.displayMapFullScreen;
            if ($scope.displayMapFullScreen) {
                $("#leafy").addClass('fullScreenMap');
            }
            else {
                $("#leafy").removeClass('fullScreenMap');
            }

            leafletData.getMap()
                .then(function (map) {
                    map.invalidateSize();
                });
        }


        function addPrintClass() {
            $("#leafy, #leafy *").addClass("printMap");
            $("#leafy *").addClass("printMapChild");
            $("#leafy").parent().addClass("printMapContainer");
            $("#mapPartsSelectBox ul, #mapPartsSelectBox ul *").addClass("printMap");
            $('body').wrapInner('<div id="printBodyWrap" />');
        }

        function MergeBranchSets(source, dest) {

            var result = [];

            _.each(source, function (e) {
                result.push(e);
            });

            _.each(dest, function (e) {
                if (!_.find(source, { branchId: e.branchId }))
                    result.push(e);
            });

            return result;
    }

        function callBranches() {
            leafletData.getMap()
                    .then(function (map) {

                        if (map._zoom > 7) {
                            var bounds = map.getBounds();

                            $scope.gettingBranches = true;
                            AdvBranchesService
                                .getBranchesInRect(bounds.getNorthWest().lat,
                                    bounds.getNorthWest().lng,
                                    bounds.getSouthEast().lat,
                                    bounds.getSouthEast().lng) //caching at service layer
                                .then(function (result) {
                                    var data = {};
                                    for (var i = 0; i < result.length; i++) {
                                        var br = result[i];
                                        data["m" + br.branchId] = {
                                            branchId: br.branchId,
                                            lat: br.latitude,
                                            lng: br.longitude,
                                            draggable: false,
                                            icon: greenIcon,
                                            message: "<a ui-sref='root.adv.institutions.summary.details({rssd: " +
                                                br.institutionRSSDId +
                                                "})'>" +
                                                br.institutionName +
                                                "</a><br/>" +
                                                (br
                                                    .branchNum ==
                                                    0
                                                    ? "<br/><span class='badge'>Head Office</span>"
                                                    : '') +
                                                "<br/>" +
                                                "<a href='#' ui-sref='root.adv.institutions.branch.details({branchId: " +
                                                br.branchId +
                                                "})'>" +
                                                br.name +
                                                "</a><br/>" +
                                                "<small>" +
                                                br.streetAddress +
                                                "<br/>" +
                                                br.cityName +
                                                ", " +
                                                br.statePostalCode +
                                                " " +
                                                br.zipcode +
                                                "</small>",
                                            getMessageScope: function () { return $scope; }

                                        };
                                    }

                                    allBranchData = data;
                                    $scope.markers = MergeBranchSets(branchData, allBranchData);

                                    hasBranches = true;
                                    $scope.gettingBranches = false;
                                });

                        } else {
                            toastr.error("Could not retrieve branch data at this zoom level.", "Please zoom in futher and try again.");
            }
        });
        }


        var hasBranches = false;
        function toggleBranches() {
            if (hasBranches) {
                $scope.showBranches = !$scope.showBranches;
                if ($scope.showBranches == false) {
                    $scope.brMarkerDatBackup = $scope.markers;
                    $scope.markers = {};
                }
                else {
                    $scope.markers = $scope.brMarkerDatBackup;
                    $scope.brMarkerDatBackup = {};
                }
               // $scope.markers = $scope.showBranches ? branchData : {};
            }
            else {
                $scope.showBranches = !$scope.showBranches;
                callBranches();
                $scope.markers = branchData;
            }        
        }

        var hasStates = false, statesGeo = null;
        function toggleStates() {
            if ($scope.noStateData) return false;
            if (hasStates) {
                $scope.geoJson = $scope.showStates ? statesGeo : {};
            } else {
                $scope.gettingStates = true;
                MarketMapService.getStates($stateParams.market)
                    .then(function (result) {
                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                        }
                        else if (result.features.features.length == 0) {
                            $scope.noStateData = true;
                        }
                        else {
                            var colors = ["red", "yellow", "blue", "orange"],
                                colorIndex = 0;

                    var geoJson = {
                                data: result.features,
                                style: function (feature) {
                                    return {
                                        fillColor: colors[feature.id % colors.length],
										weight: 2,
                                        opacity: 0.5,
                                        color: "white",
                                        dashArray: "3",
                                        fillOpacity: 0.25
                        }
                                },
                                resetStyleOnMouseout: true
                    };
                    $scope.geoJson = geoJson;
                            statesGeo = geoJson;
                            hasStates = true;
                }

                        $scope.gettingStates = false;
            });
        }
        }

        function toggleMarket() {
            $scope.layers.overlays.market.visible = $scope.showMarket;
        }

        var hasOtherMarkets = false, otherMarketsGeo = null;
        function toggleOtherMarkets() {
            if (hasOtherMarkets) {
                $scope.showOtherMarkets = !$scope.showOtherMarkets;
                $scope.geoJson = $scope.showOtherMarkets ? otherMarketsGeo : {};
            } else {
                $scope.gettingOtherMarkets = true;
                MarketMapService.getSurroundingMarkets($stateParams.market)
                    .then(function (result) {

                        if (result.hasError || result.isTimeout) {
                            toastr.error(result.isTimeout ? "Unfortunately, the server timed out retrieving your data." : "An error occurred retrieving your data.");
                            return;
                        }

                        var colors = ["red", "orange", "yellow", "green", "purple"];

                        var geoJson = {
                            data: result.features,
                            style: function (feature) {
                                return {
                                    fillColor: colors[feature.properties.index % colors.length],
                                    weight: 2,
                                    opacity: 0.5,
                                    color: "white",
                                    dashArray: "3",
                                    fillOpacity: 0.25
								}
							},
							
                            resetStyleOnMouseout: true
						};
                        $scope.geoJson = geoJson;
                        otherMarketsGeo = geoJson;

                        hasOtherMarkets = true;
                        $scope.gettingOtherMarkets = false;
                    });
        }
    }



        function setMapStyle() {

            var tileSet = null;

            _.forEach($scope.mapStyles,
                function (t) {
                    if (t.data.counties === $scope.showCounties && t.data.cities === $scope.showCities && t.data.roads === $scope.showRoads) {
                        tileSet = t;
                    return false;
                }
        });


            if (tileSet)
                $scope.tiles = tileSet;
        }
    }
})();

    var blueIcon = {
        iconUrl: '/Content/leaflet/images/marker-icon.png',
        iconSize: [25, 41],
        iconAnchor: [25, 41],
        popupAnchor: [-3, -76],
        shadowUrl: '/Content/leaflet/images/marker-shadow.png',
        shadowSize: [41, 41],
        shadowAnchor: [25, 41]
    };

    var redIcon = {
        iconUrl: '/Content/leaflet/images/marker-icon-red.png',
        iconSize: [25, 41],
        iconAnchor: [25, 41],
        popupAnchor: [-3, -76],
        shadowUrl: '/Content/leaflet/images/marker-shadow.png',
        shadowSize: [41, 41],
        shadowAnchor: [25, 41]
    };

    var greenIcon = {
        iconUrl: '/Content/leaflet/images/marker-icon-green.png',
        iconSize: [25, 41],
        iconAnchor: [25, 41],
        popupAnchor: [-3, -76],
        shadowUrl: '/Content/leaflet/images/marker-shadow.png',
        shadowSize: [41, 41],
        shadowAnchor: [25, 41]
    };




(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvMarketDetailPendingController', AdvMarketDetailPendingController);

    AdvMarketDetailPendingController.$inject = ['$scope', '$stateParams', 'AdvMarketsService', 'UserData', '$window'];

    function AdvMarketDetailPendingController($scope, $stateParams, AdvMarketsService, UserData, $window) {
        //var tempName = $scope.$parent.$parent.marketName;
        //$scope.$parent.market.definition.name = "Pending Transactions for " + tempName;
        $scope.$parent.hideEditDiv = false;
        $scope.runDate = new Date();
        $scope.marketID = $stateParams.market;

        activate();

        function activate() {
            AdvMarketsService.getMarketPendingById({ marketId: $stateParams.market, getPending: true }).then(function (result) {
                if (result.length > 0) {
                    $scope.PendingData = result;
                    $scope.pendingReady = true;
                    $scope.marketLoaded = true;
                }
                else
                {
                    $scope.pendingReady = false;
                }
                $scope.pending = true;
            });
        }

        $scope.applyChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.sortBy = sortBy.sort.predicate;
                $scope.asc = !sortBy.sort.reverse;
            } else {
                $scope.sortBy = 'survivorName';
                $scope.asc = true;
            }
        }

        $scope.printView = function () {
            var data = [
                $scope.marketID,
                document.getElementById('quickSearch').value,
                false,
                $scope.sortBy,
                $scope.asc,
                document.getElementById('quickSearch').value == "" ? "" : 'Filtered by ' + document.getElementById('quickSearch').value
            ];
            var reportType = 'pendingtransactionsmarkets';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }




    }

    angular
 .module('app')
   .filter('marketPendingFilter', function () {
       return function (dataArray, searchTerm) {
           if (!dataArray) return;
           if (searchTerm.$ == undefined) {
               return dataArray
           } else {
               var term = searchTerm.$.toLowerCase();
               return dataArray.filter(function (item) {
                   return checkVal(item.survivorName, term)
                       || checkVal(item.survivorRssdId.toString(), term)
                       || checkVal(item.memoText, term)
               });
        }
       }

       function checkVal(val, term) {
           if (val == null || val == undefined)
               return false;

           return val.toLowerCase().indexOf(term) > -1;
    }

   });
})();;

(function () {
    'use strict';

    angular
      .module('app')
      .factory('AdvPendingService', AdvPendingService);

    AdvPendingService.$inject = ['$http', '$log'];

    function AdvPendingService($http, $log) {
        var service = {
            getPendingTransactions: getPending,
            getPendingSingleTransaction: getPendingSingle,
            getPendingTransaction: getPendingRecord,
            addPendingTransaction: addPending,
            editPendingTransaction: editPending,
            getDeletedTransactions: deletePending,
            getPendingTopholds: getPendingTHF,
            getMarketNumberList: getMarketNumberList,
			getPendingTHAcqTH: getPendingTHAcqTH,
			getPendingDeNovo: getPendingDeNovo
        };

        return service;
        ////////////////		

		function getPending(data) {
            return $http.get('/api/pending/GetPending')
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning pending transaction data", result);
                });
        }
        function getPendingSingle(data) {
			return $http.get('/api/pending/GetPendingSingle', { params: { pendingTransId: data.pendingTransId} })
                .then(function Success(result) {
                   $log.info("success" +result.data);
                    return result;
                }, function Failure(result) {
                    $log.error("Error returning pending transaction data", result);
                });
        }

        function getPendingRecord(data) {
            return $http.get('/api/pending/GetPending', { params: { SurvivorRssdId: data.SurvivorRssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning pending transaction record", result);
                });
        }
        function addPending(data) {
            return $http.post('/api/pending/AddPending', data, { params: { transactionMode: data.TransactionMode, transactionId: data.TransactionId} })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error adding pending transaction data", result);
                });
        }

        function editPending(data) {
            return $http.post('/api/pending/AddPending', data, { params: { TransactionMode: data.TransactionMode, transactionID: data.TransactionId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error updating pending transaction data", result);
                });
        }

        function deletePending(data) {
			return $http.get('/api/pending/DeletePending', { params: { pendIds: data } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error deleting pending transaction data", result);
                });
        }

        function getPendingTHF(data) {
            return $http.get('/api/pending/GetPendingTopholds', { params: { SurvivorRssdId: data.SurvivorRssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning pending tophold formations data", result);
                });
        }


        function getPendingTHAcqTH(data) {
            return $http.get('/api/pending/GetPendingTopholdsAcquiredByTophold', { params: { SurvivorRssdId: data.SurvivorRssdId, NonSurvivorRssdId: data.NonSurvivorRssdId } })
                .then(function Success(result) {
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning pending tophold Acquire tophold data", result);
                });
		}


		function getPendingDeNovo(data) {
			return $http.get('/api/pending/GetPendingDeNovo', { params: { FDICCertNum: data.FDICCertNum } })
				.then(function Success(result) {
					return result.data;
				}, function Failure(result) {
					$log.error("Error returning pending De Novo institution data", result);
				});
		}

        

        function getMarketNumberList(RSSDId) {
            return $http.get('/api/pending/market-number-list', { params: { RSSDId: RSSDId } })
                .then(function Success(result) {
                    $log.info("sudcess - " + result.data);
                    return result.data;
                }, function Failure(result) {
                    $log.error("Error returning market number list", result);
                });
        }

    }
})();
;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('PendingTxnsAddController', PendingTxnsAddController);

	PendingTxnsAddController.$inject = ['$scope', '$state', '$stateParams', 'StatesService', 'AdvPendingService', 'AdvMarketsService', 'toastr', '$log', 'UserData', '$uibModal'];

	function PendingTxnsAddController($scope, $state, $stateParams, StatesService, AdvPendingService, AdvMarketsService, toastr, $log, UserData, $uibModal) {

		$scope.defaultDeNovoOrgName = "None/De Novo";
		$scope.criteria = {};
		$scope.criteria.orgName = "";
		$scope.criteria.rssdId = "";
		$scope.criteria.fdicCertNum = "";
        $scope.criteria.targetIds = "";
		$scope.criteria.marketNums = "";
		$scope.criteria.isApproved = false;
		$scope.criteria.isDeNovo = false;	
		$scope.criteria.state = "";
		$scope.criteria.county = "";
		$scope.criteria.city = "";		
        $scope.isTopHoldFormation = false;
        $scope.pendingAdd = true;
        $scope.pendingAdded = false;
        $scope.Loading = false;
        $scope.successfullyUpdated = false;
        $scope.pendingError = true;
        $scope.errorMessage = "No Errors.";
        $scope.isEditing = false;
        $scope.MarketsReady = true;
		$scope.errorVisible = false;
		$scope.states = [];
		$scope.stateCopyData = [];
		$scope.statesLoaded = false;
		$scope.stateCounties = [];
		$scope.countyCities = [];

       
        $scope.UserData = UserData;
        $scope.ListOfMarketIds = [];
        $scope.ListOfTargetIds = [];
        $scope.TitleMessage = "";
        $scope.TopholdFormation = "";
        $scope.cancel = cancel;
        $scope.setTopHoldFormation = function () {
            if (!$scope.isTopHoldFormation) {
                $scope.isTopHoldFormation = true;
            }
            else {
                $scope.isTopHoldFormation = false;
            }
        };

        activate();
        function activate() {
            $scope.criteria.rssdId = "";
            $scope.criteria.targetIds = "";
			$scope.criteria.marketNums = "";	

			StatesService.getStateSummaries({ includeDC: true, includeTerritories: true }).then(function (result) {
				$scope.states = result;
				$scope.stateCopyData = result;
				$scope.statesLoaded = true;
			});

            window.scrollTo(0, 0);
		};


        $scope.isStoredTopHoldFormation = function () {
            if (!$scope.isTopHoldFormation) {
                return false;
            }
            else {
                $scope.TopholdFormation = "This is a Tophold Formation!";
                return true;
            }
		};

		$scope.loadCountiesByState = function () {
			$scope.criteria.city = null;
			$scope.criteria.county = null;

			var data = { stateFIPSId: null };
			if ($scope.criteria.state) {
				data = { stateFIPSId: $scope.criteria.state.fipsId };

				StatesService.getCountySummaries(data).then(function (result) {
					$scope.stateCounties = result;
					//$('#county').focus();
				});
			}
		}

		$scope.reloadStateCountyCityLists = function () {
			if ($scope.criteria.state) {
				data = { stateFIPSId: $scope.criteria.state.fipsId };

				StatesService.getCountySummaries(data).then(function (result) {
					$scope.stateCounties = result;
					data = { countyId: $scope.criteria.county.countyId };
					StatesService.getCitySummaries(data).then(function (result) {
						$scope.countyCities = result;
					});
				});
			}
		}

		$scope.loadCitiesByCounty = function () {
			$scope.criteria.city = null;
			if ($scope.criteria.county != null) {
				data = { countyId: $scope.criteria.county.countyId };

				StatesService.getCitySummaries(data).then(function (result) {
					$scope.countyCities = result;
					//$('#city').focus();
				});
			}
		}

		$scope.loadMarketNumByCity = function () {
			if ($scope.criteria.city != "") {
				AdvMarketsService.getMarketNumber($scope.criteria.city.cityId).then(function (result) {
					if (!isNaN(result)) { $scope.criteria.marketNums = result.toString(); }
				});
			}
		}



		$scope.forceCertNumber = function () {
			$scope.criteria.fdicCertNum = $scope.criteria.fdicCertNum.replace(/\D/g, '');			
		};

        $scope.$parent.transactionMode = "Add Pending Transaction";

		if (($stateParams.pendingTxnId != null)) {
     
            var data = {
				pendingTransId: $stateParams.pendingTxnId
            };
            
            $scope.Loading = true;

            AdvPendingService.getPendingSingleTransaction(data).then(function (result) {
                $scope.Loading = false;
                $scope.$parent.transactionMode = "Edit Pending Transaction";
                $scope.isEditing = true;
                $scope.pendingAdd = true;
                $scope.pending = result.data;
				$scope.criteria.rssdId = result.data.survivorRssdId;
				$scope.criteria.fdicCertNum = result.data.survivorFDICCertNum;
				$scope.criteria.isDeNovo = (result.data.isDeNovo == true) || (result.data.survivorFDICCertNum && result.data.survivorFDICCertNum > 0);
                $scope.criteria.targetIds = (result.data.targetRSSDIds.length > 0 ? _.join(result.data.targetRSSDIds, " , ") : result.data.targetRSSDIds);
                $scope.criteria.marketNums = (result.data.marketIds.length > 0 ? _.join(result.data.marketIds, " , ") : result.data.marketIds);
				$scope.criteria.memo = result.data.note; //.replace(/<br ?\/?>/g, "\n");
				$scope.criteria.isApproved = result.data.isApproved;
				$scope.isTopHoldFormation = result.data.isTopholdFormation;
				$scope.criteria.denovoAdrSummary = result.data.denovoAdrSummary;  

				if ($scope.criteria.isDeNovo && $scope.criteria.denovoAdrSummary != undefined) {
					$scope.criteria.orgName = result.data.denovoName;

					// populate the county drop-down and set current county selection
					$scope.criteria.city = $scope.criteria.denovoAdrSummary.citySummary;
					$scope.criteria.county = $scope.criteria.denovoAdrSummary.countySummary;
					$scope.criteria.state = $scope.criteria.denovoAdrSummary.stateSummary;

					$scope.reloadStateCountyCityLists();
				}
            });

        } else {
        }
        function convertToArray() {
            if ($scope.criteria.marketNums != null) {
                if ($scope.criteria.marketNums.length > 0) {
                    if ($scope.criteria.marketNums.indexOf(",") > -1)
                        $scope.ListOfMarketIds = $scope.criteria.marketNums.split(",");
                    else {
                        $scope.ListOfMarketIds[0] = $scope.criteria.marketNums;
                    }
                }
                else {
                    $scope.ListOfMarketIds = [];
                    $scope.criteria.marketNums = "";
                }
            }
            else {
                $scope.ListOfMarketIds= [];
                $scope.criteria.marketNums = "";

            }
            if ($scope.criteria.targetIds != null) {
                if ($scope.criteria.targetIds.length > 0) {
                    if ($scope.criteria.targetIds.indexOf(",") > -1)
                        $scope.ListOfTargetIds = $scope.criteria.targetIds.split(",");
                    else
                        $scope.ListOfTargetIds[0] = $scope.criteria.targetIds;
                }
                else {
                    $scope.ListOfTargetIds = [];
                    $scope.criteria.targetIds = "";
                 }

            }
            else {
                $scope.ListOfTargetIds = [];
                $scope.criteria.targetIds = "";
            }         
                
		}


        $scope.AddSubmit = function () {
			var errMsgs = $scope.validateRequired();
			var numErrors = errMsgs.length;
			if (numErrors > 0) {
				for (var i = 1; i <= numErrors; i++) {
					toastr.error(errMsgs[numErrors - i], '', { allowHtml: true });
				}				
				return;
			}

			convertToArray();          

			if ($scope.$parent.transactionMode == "Edit Pending Transaction") {

				var data = {
					SurvivorRssdId: $scope.criteria.isDeNovo ? "0" : $scope.criteria.rssdId,
					SurvivorFDICCertNum: $scope.criteria.isDeNovo ? $scope.criteria.fdicCertNum : null,
                    IsTopholdFormation: $scope.isTopHoldFormation,
                    Note: $scope.criteria.memo.replace(/\r\n|\r|\n/g, '\n'),
                    MarketIds: $scope.ListOfMarketIds,
                    TargetRSSDIds: $scope.ListOfTargetIds,
                    TransactionMode: "Edit",
					TransactionId: $stateParams.pendingTxnId,
					IsApproved: $scope.criteria.isApproved,
					OrgName: ($scope.criteria.isDeNovo && trimString($scope.criteria.orgName) == "") ? $scope.defaultDeNovoOrgName : trimString($scope.criteria.orgName),
					CityId: ($scope.criteria.isDeNovo && $scope.criteria.city != undefined) ? $scope.criteria.city.cityId : null,
					FDICCertNum: $scope.criteria.isDeNovo ? $scope.criteria.fdicCertNum : null,
					DenovoName: ($scope.criteria.isDeNovo && trimString($scope.criteria.orgName) == "") ? $scope.defaultDeNovoOrgName : trimString($scope.criteria.orgName),
					DenovoCityId: ($scope.criteria.isDeNovo && $scope.criteria.city != undefined) ? $scope.criteria.city.cityId : null,
				};

                editPendingData(data);
              
            } else {
               
				var data = {
						SurvivorRssdId: $scope.criteria.isDeNovo ? "0" : $scope.criteria.rssdId,
						SurvivorFDICCertNum: $scope.criteria.isDeNovo ? $scope.criteria.fdicCertNum : null,
						IsTopholdFormation: $scope.isTopHoldFormation,
						Note: $scope.criteria.memo.replace(/\r\n|\r|\n/g, '\n'),
						IsApproved: $scope.criteria.isApproved,
						MarketIds: $scope.ListOfMarketIds,
						TargetRSSDIds: $scope.ListOfTargetIds,
						DenovoName: ($scope.criteria.isDeNovo && trimString($scope.criteria.orgName) == "") ? $scope.defaultDeNovoOrgName : trimString($scope.criteria.orgName),
						DenovoCityId: ($scope.criteria.isDeNovo && $scope.criteria.city != undefined) ? $scope.criteria.city.cityId : null,
						TransactionMode: "Add",
						transactionId: ""
					//denovoOrg:
					//{
					//	FDICCertNum: $scope.criteria.isDeNovo ? $scope.criteria.fdicCertNum : null,
					//	OrgName: ($scope.criteria.isDeNovo && trimString($scope.criteria.orgName) == "") ? $scope.defaultDeNovoOrgName : trimString($scope.criteria.orgName),
					//	CityId: ($scope.criteria.isDeNovo && $scope.criteria.city != undefined) ? $scope.criteria.city.cityId : null
					//}							
				};			


                addPendingData(data);         
            }
           
		};

		function trimString(str) {
			return str.replace(/^\s+|\s+$/g, '');
		}

        function addPendingData(data) {
            $scope.Loading = true;

            AdvPendingService
                .addPendingTransaction(data).then(function (result) {

                    $scope.pendingAdded = result.pendingLoaded;
                    $scope.pendingError = !result.pendingLoaded;

                    if ($scope.pendingError == false) {
                        toastr.success("Pending Transaction has been added!");
                        $scope.pendingAdd = false;

                        $scope.TitleMessage = "Successfully Added Pending Transaction."
                        $scope.successfullyUpdated = true;
                        
                        window.scrollTo(0, 0);
                    }
                    else {

						toastr.error(result.errorMessage || "Please try again or contact support.");
                        $scope.errorMessage = result.errorMessage;
                    }

                    $scope.Loading = false;
                });
        }

        function editPendingData(data) {
            $scope.Loading = true;
            AdvPendingService.editPendingTransaction(data).then(function (result) {

                $scope.pendingAdd = result.pending;
                $scope.pendingAdded = result.pendingLoaded;
                $scope.pendingError = !result.pendingLoaded;

                if ($scope.pendingError == false) {
                    toastr.success("Pending Transaction has been edited!");
                    $scope.TitleMessage = "Successfully Edited Pending Transaction."
                 
                    $scope.successfullyUpdated = true;
                    window.scrollTo(0, 0);
                }
                else {
                    toastr.error("Error Encountered!", result.errorMessage || "Please try again or contact support.");
                    $scope.errorMessage = result.errorMessage;
                }
                $scope.Loading = false;
            });
        }

        $scope.openModalTargetIds = function () {
            $uibModal.open({
                templateUrl: 'AppJs/advanced/pending/views/addMultiRssdIds.html',
                controller: ["$uibModalInstance", "$scope", "UserData", "AdvPendingService",  function ($uibModalInstance, $scope, UserData, AdvPendingService) {
                    $scope.UserData = UserData;
                    $scope.targetIds = null;
                    //$scope.currentTargetIds = (PendingTxnsAddController.criteria.targetIds == null ? null : PendingTxnsAddController.criteria.targetIds)

                    $scope.saveChanges = function () {
                        $("#rssdPlaceholder :checkbox:checked").each(function () {
                            $scope.targetIds = ($scope.targetIds == null ? $(this).val() : $scope.targetIds += " , " + $(this).val());
                            $log.info("Value", $(this).val());
                        });
                        $uibModalInstance.close($scope.targetIds);
                    };
                }]
            }).result.then(function (result) {
                $log.info("result", result);
                $scope.criteria.targetIds = result;
                $scope.MarketsReady = false;
                AdvPendingService
                    .getMarketNumberList($scope.criteria.targetIds)
                    .then(function (data) {
                        $log.info(data);

                        $scope.criteria.marketNums = data;
                        $scope.MarketsReady = true;
                    });
            });
		}

		$scope.validateRequired = function() {
			var errorMsgs = [];
			if (!$scope.criteria.isDeNovo && (!$scope.criteria.rssdId || isNaN($scope.criteria.rssdId))) {
				errorMsgs.push("Survivor RSSDId is required.");
			}
			if ($scope.criteria.isDeNovo && (!$scope.criteria.fdicCertNum || isNaN($scope.criteria.fdicCertNum))) {
				errorMsgs.push("For De Novo institutions, FDIC certificate number is required.");
			}
			if (!$scope.criteria.memo || trimString($scope.criteria.memo).length == 0) {
				errorMsgs.push("Memo text is required.");
			}
			if ($scope.criteria.isDeNovo && ($scope.criteria.state=="" || isNaN($scope.criteria.state.fipsId))) {
				errorMsgs.push("State is required for de novo organizations.");
			}
			if ($scope.criteria.isDeNovo && ($scope.criteria.county == "" || isNaN($scope.criteria.county.countyId))) {
				errorMsgs.push("County is required for de novo organizations.");
			}
			if ($scope.criteria.isDeNovo && ($scope.criteria.city == "" || isNaN($scope.criteria.city.cityId))) {
				errorMsgs.push("City is required for de novo organizations.");
			}

			return errorMsgs;
		}

        $scope.targetsChosen = function (targets) {
            $scope.criteria.targetIds = targets;
            $scope.getMarketNumber();
        };

        $scope.getMarketNumber = function () {
            $log.info("event", $scope.criteria.targetIds);
            $scope.MarketsReady = false;
            AdvPendingService
                .getMarketNumberList($scope.criteria.targetIds)
                .then(function (data) {
                    $scope.criteria.marketNums = data;
                    $scope.MarketsReady = true;
                });
        };
        $scope.ValidateValue = function () {
            if ($scope.criteria.rssdId == "") {
                $scope.errorVisible = true;
            }
            else
                $scope.errorVisible = false;

        }
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }
        function cancel() {
            $state.go("root.adv.pending", null, { reload: true });
        }
    }
})();;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('PendingTxnsController', PendingTxnsController);

    PendingTxnsController.$inject = ['$scope', '$rootScope', '$state', '$stateParams','StatesService', 'AdvPendingService', 'UserData', 'toastr', '$window'];

    function PendingTxnsController($scope, $rootScope, $state, $stateParams,StatesService, AdvPendingService, UserData, toastr, $window) {
        $scope.title = 'PendingTxnsController';
        $scope.txnIds = [];
        $scope.AccordionView = true;
        $scope.ConfirmationView = false;
        $scope.DeletedMessage = "";
        $scope.TableView = false;
        $scope.PendingData = [];
        $scope.DeletedPendingData = [];
        $scope.pending = [];
        $scope.pendingById = [];
		$scope.topholdFormation = [];
		$scope.denovoInsts = [];
        $scope.outsideUS = [];
        $scope.pendingByState = [];
        $scope.dropdownstates = [];
        $scope.totalItems = 0;
        $scope.ItemsPerPage = 10;
        $scope.currentPage = 1;
		$scope.filterTitle = "";
		$scope.selectedFilterButton = "all";
		angular.extend($scope, {
			isChecked: function (id) {
				return $scope.txnIds.indexOf(id) > -1;
			},
			toggle: function (id) {
				var idx = $scope.txnIds.indexOf(id);
				if (idx > -1) {
					$scope.txnIds.splice(idx, 1);
				}
				else {
					$scope.txnIds.push(id);
				}
			},
			transactionMode: "Add Pending Transaction",
			deleteTransactions: function () {
				if ($scope.txnIds.length > 0) {
					var delData = $scope.txnIds;
					var txnIDs = "";
					for (var i = 0; i < delData.length; i++) {
						txnIDs += delData[i] + ",";
					}
					$scope.txnIds = txnIDs.slice(0, -1);
					deleteTransaction($scope.txnIds);
				}
				else {
					toastr.success("No Pending Transactions have been selected!");
				}
			},
			isIndex: isOnIndexPage($state.current),
			pendingReady: false,
			filter: "all",
			ViewFilter: "Accordion",
			pendingByState: [],
			pendingByIds: [],
			districtIds: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
			hasDistrictIdFilter: function () {
				return _.indexOf(this.districtIds, this.filter) > -1
			},
			views: ['Accordion', 'Table'],

			hasViewFilter: function () {

				return this.ViewFilter;
			},
			setViewFilter: function (view, btnName) {
				$scope.selectedFilterButton = btnName;
				$scope.ViewFilter = view;
				switch ($scope.ViewFilter) {
					case "Accordion":
						$scope.pending = $scope.pendingByState;
						$scope.filter = "all";
						$scope.hasStateFilter();
						$scope.AccordionView = true;
						$scope.TableView = false;
						break;
					case "Table":
						$scope.AccordionView = false;
						$scope.TableView = true;
						$scope.filter = "";
						break;
				}
			},
			states: [],
			hasStateFilter: function () {				
				return _.indexOf(this.states, this.filter) > -1;
			},

			isFilterBtnActive: function (btnName) {
				return ($scope.selectedFilterButton == btnName);
			},

            setStateFilter: function (state, btnName) {
				$scope.selectedFilterButton = btnName;
				$scope.filter = state;
                $scope.filterTitle = 'in ' + state;
                $scope.pending = [];
                var stateChunk = _.find($scope.pendingByState, { survivorStateName: state });
                if (stateChunk) {
                    //stateChunk.isOpen = true;
                    var st = stateChunk.data[0].survivorStateName;
                    var chunk2 = _.filter(stateChunk.data, { survivorStateName: st });
                    $scope.pending.push({ survivorStateName: st, data: chunk2 });
                }
            },
            setDistrictIdFilter: function (dId, btnName) {
				$scope.selectedFilterButton = btnName;
				$scope.filter = dId;
                $scope.filterTitle = 'in District ' + dId;
                var idChunk = _.find($scope.pendingById, { survivorDistrictId: dId });
                $scope.pending = [];
                if (idChunk) {
                    for (var i = 0; i < idChunk.data.length; i++) {
                        var st = idChunk.data[i].survivorStateName;
                        var stInt = _.find($scope.pending, { survivorStateName: st });

                        if (typeof stInt == "undefined") {//need to add district data to pendingList
                            var chunk2 = _.filter(idChunk.data, { survivorDistrictId: dId, survivorStateName: st });
                            $scope.pending.push({ survivorStateName: st, data: chunk2 });
                        } else { }
                    }

                }
            },

            showAllData: function (btnName) {
                $scope.pending = $scope.pendingByState;
                $scope.filter = "all";
                $scope.filterTitle = 'All';
				$scope.hasStateFilter();
				$scope.selectedFilterButton = btnName;
            },
			showTopholdFormations: function (btnName) {
				$scope.selectedFilterButton = btnName;
                $scope.filterTitle = 'for TopHold Formations';
                $scope.filter = "TopHold Formations";
                $scope.pending = [];
                //$scope.topholdFormation = [];

                var stateChunk = $scope.topholdFormation;// _.find($scope.topholdFormation, {isTopholdFormation: true});
                if (stateChunk) {

                    for (var i = 0; i < stateChunk.length; i++) {
                        var st = stateChunk[i].survivorStateName;
                        var stInt = _.find($scope.pending, { survivorStateName: st });

                        if (typeof stInt == "undefined") {
                            var chunk2 = _.filter(stateChunk, { survivorStateName: st });
                            $scope.pending.push({ survivorStateName: st, data: chunk2 });
                        } else { }
                    }

                }
			},
			showDeNovoInsts: function (btnName) {
				$scope.selectedFilterButton = btnName;
				$scope.filterTitle = 'for De Novo Institutions';
				$scope.filter = "De Novo Institutions";
				$scope.pending = [];

				var stateChunk = $scope.denovoInsts; 
				if (stateChunk) {

					for (var i = 0; i < stateChunk.length; i++) {
						var st = stateChunk[i].survivorStateName;
						var stInt = _.find($scope.pending, { survivorStateName: st });

						if (typeof stInt == "undefined") {
							var chunk2 = _.filter(stateChunk, { survivorStateName: st });
							$scope.pending.push({ survivorStateName: st, data: chunk2 });
						} else { }
					}

				}
			},
            showDistrictIds: true,
            clearDistrictIdFilter: function () {
                if (!this.showDistrictIds && this.hasDistrictIdFilter())
                    this.filter = "all";
            },
            pendingFilter: function (pend) {
                switch ($scope.filter) {
                    case "all":
                        $scope.pending = $scope.pendingByState;
                        return true;
                        break;
                    case "":
                        break;
                    case "":
                        break;
                    case "":
                        break;
                    default:
                        return true;
                }
            },
            closeOpenPendingTransaction: function (open) {
                angular.forEach($scope.pending, function (obj, index) {
                    obj.isOpen = open === true ? true : open === false ? false : !obj.isOpen;
                });
                
            }
        });
        activate();

        function activate() {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                window.scrollTo(0, 0);
                $scope.isIndex = isOnIndexPage(toState);

            });

            AdvPendingService.getPendingTransactions().then(function (result) {    
                $scope.pending = result;
                $scope.PendingData = result;
                 
                $scope.totalItems = $scope.PendingData.length;
                $scope.DataPages = _.chunk($scope.PendingData, $scope.ItemsPerPage);
              

                var x = 0;
                var y = 0;
				var z = 0;
				var denovCount = 0;

                angular.forEach(result, function (val, key) {
                    var grouping = val.grouping;
                    var state = val.survivorStateName; // val.survivorStatePostal;
                    // val.memoText = val.memoText.replace(/<br/>/g/, '\n');

                    switch (grouping) {
                        // ExistingTHInsideUA = 1
                        case 1:
                          //  $scope.pendingByState[x] = val;
                            //x++;
                            break;

                            //ExistingTHOutsideUS = 2
                        case 2:
                            $scope.outsideUS[y] = val;
                            y++;
                            break;

                            // THFormation = 3
                        case 3:
                            $scope.topholdFormation[z] = val;
                            z++;
							break;
						case 4:
							$scope.denovoInsts[denovCount] = val;
							denovCount++;
							break;
                    }
                    

                    if (_.indexOf($scope.states, state) == -1) {
                        //if(state != "TopHold Formations")
                            $scope.states.push(state);
                    }
                  });
					// $scope.states.sort();
					for (var i = 0; i < $scope.states.length; i++) {
						var state = $scope.states[i];
						$scope.chunk = _.filter(result, { survivorStateName: state });   
						$scope.pendingByState.push({ survivorStateName: state, data: $scope.chunk });
					}
					var index = $scope.states.indexOf("TopHold Formations");
					if (index > -1) { $scope.states.splice(index, 1); }
					index = $scope.states.indexOf("De Novo");
					if (index > -1) { $scope.states.splice(index, 1); }


                    $scope.dropdownstates = $scope.states;

                    for (var i = 0; i < $scope.districtIds.length; i++) {
                        var districtId = ($scope.districtIds[i]);
                        var chunk = _.filter(result, { survivorDistrictId: districtId });
                        if (typeof chunk[0] == "undefined") {
                            $scope.pendingByIds.push({ survivorDistrictId: districtId, survivorStateName: "", data: chunk });
                        }
                        else {
                            $scope.pendingByIds.push({ survivorDistrictId: districtId, survivorStateName: chunk[0].survivorStateName, data: chunk });
                        }
                        
                    }

                    $scope.pendingById = $scope.pendingByIds;
                    $scope.pending = $scope.pendingByState;
                    $scope.pendingReady = true;
                });
            }
        function PageCount() {
            return Math.ceil( $scope.pending.length / $scope.ItemsPerPage);
        }
        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.pending";
        }
        function deleteTransaction(data) {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            });
            $scope.pendingReady = false;
            AdvPendingService.getDeletedTransactions(data).then(function (result) {
                $scope.pendingError = result.pendingLoaded;
                if ($scope.pendingError == false) {
                    toastr.success(result.errorMessage);
                    // $state.go($state.$current, null, { reload: true });
                    deletedTransactionInformation();
                }
                else {
                    toastr.error( result.errorMessage || "Please try again or contact support.");
                    $scope.errorMessage = result.errorMessage;
                }
                $scope.pendingReady = true;
                window.scrollTo(0, 0);
            });
        }
        function deletedTransactionInformation() {
            var deletedPending = [];
            //var pendingData = [];

            var ids = [];
            ids = $scope.txnIds.split(",");

            for (var i = 0; i < ids.length; i++) {
                var rssidValue = parseInt(ids[i]);
                deletedPending[i] = _.find($scope.PendingData, { pendingTransactionId: rssidValue });
               // deletedPending[i].memoText = deletedPending[i].replace('<br/>', '\n')
            }
            if (deletedPending != null) {
                $scope.DeletedPendingData = deletedPending;
                $scope.DeletedMessage = (deletedPending.length > 1 ? "Successfully Deleted the Following Pending Transactions" : "Successfully Deleted the Following Pending Transaction");
                $scope.ConfirmationView = true;
                $scope.AccordionView = true;
                $scope.TableView = true;
               
            }
        }
        $scope.backToList = function () {
            $state.go($state.$current, null, { reload: true });
        }
        $scope.printDiv = function (divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800');
            popupWin.document.open();
            popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
            popupWin.document.close();
        }

        $scope.applyChange = function (sortBy) {
            if (sortBy.sort.predicate != undefined) {
                $scope.sortBy = sortBy.sort.predicate;
                $scope.asc = !sortBy.sort.reverse;
            } else {
                $scope.sortBy = 'survivorStatePostal';
                $scope.asc = true;
            }
        }


        $scope.printView = function() {
            var data = [
                null,
                $scope.filter == "" ? "all" : $scope.filter,
                "true",
                $scope.sortBy,
                $scope.asc,
                $scope.filterTitle == "" ? "All" : $scope.filterTitle
                /* 
                    Add a year filter here when the filtering changes or you can just append to the line above to add 
                    year to the display message of how data is being displayed.
                */
            ];
            var reportType = 'pendingtransactions';

            var jData = angular.toJson(data);

            $window.open('/reportserver/generateanddisplayreport?reportType=' + reportType + '&params=' + jData, '_blank');
        }


        $scope.MoveUp = function () {
            window.scrollTo(0, 0);
        }
    }

    angular
  .module('app')
    .filter('pendingFilter', function () {
        return function (dataArray, searchTerm) {
            if (!dataArray) return;
            if (searchTerm.$ == undefined) {
                return dataArray
            } else {
                var term = searchTerm.$.toLowerCase();
                return dataArray.filter(function (item) {
                    return checkVal(item.survivorRssdId.toString(), term)
                        || checkVal(item.survivorName, term)
                });
            }
        }

        function checkVal(val, term) {
            if (val == null || val == undefined)
                return false;

            return val.toLowerCase().indexOf(term) > -1;
        }
        function checkNum(val, term) {
            if (val == null || val == undefined)
                return false;
            return val == term;
        }
    });
})();


;
(function () {
    'use strict';

    angular
        .module('app')
        .controller('AdvReportsController', AdvReportsController);

    AdvReportsController.$inject = ['$scope', '$http', '$log'];

    function AdvReportsController($scope, $http, $log) {
 
        //$http.get('/advanced/reports/Reports.json')
        // .success(function (data) {
        //     console.log('data1' + data.Reports)
        //     $scope.Reports = data.;
        // })
        // .error(function (data, status, headers, config) {
        //     //  Do some error handling here
        // });


        $scope.Reports = [];
  


        //$scope.Reports = [{
        //    ReportName: 'HHI For All Markets',
        //    ReportURL: '/report/getHHIForAllMarkets',
        //    Format: 'xls',
        //    HelpInforamtion: 'Deposit and HHI information for all defined banking markets in CASSIDI',
        //    HelpURL: '/AppJs/advanced/reports/templates/HHIForAllMarkets.html'
        //}, {
        //    ReportName: 'Foreign Topholds and Subs list',
        //    ReportURL: '/report/getForeignTopHoldsList',
        //    Format: 'xls',
        //    HelpInforamtion: 'Topholds in CASSIDI headquartered outside of the U.S. and their subsidiary banks and thrifts.',
        //    HelpURL: '/AppJs/advanced/reports/templates/ForeignTopHolds.html'
        //}, {
        //    ReportName: 'Foreign Topholds and Subs list',
        //    ReportURL: '/report/getForeignTopHoldsList',
        //    Format: 'xls',
        //    HelpInforamtion: 'Topholds in CASSIDI headquartered outside of the U.S. and their subsidiary banks and thrifts.',
        //    HelpURL: '/AppJs/advanced/reports/templates/ForeignTopHolds.html'
        //}];



    };
}());
;

(function () {
    angular.module('app')
           .directive('savedInst', savedRssd);

    savedRssd.$inject = ['$log'];

    function savedRssd($log) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            template: ''
        };
        return directive;

        function link(scope, element, attrs) {
        }
    };
})();
;

(function () {
    'use strict';

    angular
      .module('app')
      .controller('AdvStructureWizardController', AdvStructureWizardController);

    AdvStructureWizardController.$inject = ['$scope', '$rootScope', '$state', 'StatesService', 'AdvInstitutionsService', '$log', '$uibModalInstance', '$timeout'];

    function AdvStructureWizardController($scope, $rootScope, $state, StatesService, AdvInstitutionsService, $log, $uibModalInstance, $timeout) {
        angular.extend($scope, {
            isIndex: isOnIndexPage($state.current)
        });

        $scope.lookupMode = "";
        $scope.isActivating = true;

        activate();

        function activate() {

            $rootScope.isInWizard = true;

            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                $scope.isIndex = isOnIndexPage(toState);
            });

            StatesService.statesPromise.then(function (result) {
                $scope.states = result;
                $scope.statesLoaded = true;
            });

            $scope.isActivating = false;

          
            $timeout(function () {
                $('#rssdIdEntry').focus();
            }, 750);

            $scope.$on('transactionFinished', function (event, args) {
                $scope.lookupMode = "";
                $scope.lookup = null;
                $scope.criteria.rssdId = "";

                $timeout(function () {
                    $('#rssdIdEntry').focus();
                }, 250);
            });
        }


        $scope.processAction = function(actioname)
        {
            $scope.lookupMode = actioname;
            $state.params.mode = actioname;
            $state.params.rssd = $scope.criteria.rssdId;
            $state.params.BankRSSDID = $scope.criteria.rssdId;
            $scope.criteria.lookupMode = actioname;
        }
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.restart = function() {   
            $scope.$broadcast('transactionFinished');
        }

        function isOnIndexPage(stateToCheck) {
            return stateToCheck.name == "root.adv.institutions";
        }
    }
})();

                

;
(function () {
    angular.module('app')
           .directive('instLookup', instLookup);

    instLookup.$inject = ['$log', 'AdvInstitutionsService', '$timeout'];

    function instLookup($log, AdvInstitutionsService, $timeout) {
        // Usage:
        // 
        // Creates:
        // 
        var directive = {
            link: link,
            restrict: 'E',
            replace: true,
            templateUrl: '/AppJs/advanced/structure/views/instLookup.html',
            scope: {
                rssdValue: "=",
                inst: "=",
                formLabel: "@",
                inputId: "@"
            }
        };
        return directive;

        function link(scope, element, attrs) {

            scope.inputChangedPromise = null;
            scope.lookingUp = false;
            scope.inst = null;

            if (scope.formLabel  == null || scope.formLabel == '')
                scope.formLabel = "RSSDID#";

            if (scope.inputId == null || scope.inputId == '')
                scope.inputId = "rssdid";

            scope.$watch('rssdValue', function (newValue, oldValue) {
                if (newValue) {

                    if (scope.inputChangedPromise) {
                        $timeout.cancel(scope.inputChangedPromise);
                    }

                    scope.lookingUp = true;

                    scope.inputChangedPromise = $timeout(function () {

                        AdvInstitutionsService
                            .getInstitutionData({
                                rssdId: newValue,
                                getDetail: true,
                                getBranches: false,
                                getOperatingMarkets: false,
                                getHistory: false
                            })
                            .then(function (result) {
                                if (result.definition != null)
                                    scope.inst = result.definition;
                                else
                                    scope.inst = null;

                                scope.lookingUp = false;
                            });

                    },
                        500);

                } else {
                    scope.inst = null;
                }
            });
          
        }
    };
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .factory('UserPassChangeService', UserPassChangeService);

    UserPassChangeService.$inject = ['$uibModal', '$log'];

    function UserPassChangeService($uibModal, $log) {
        var service = {
            openModal: openPassChangeModal
        };

        return service;
        ////////////////

        function openPassChangeModal(passChangeRequired, userCreds) {
            return $uibModal.open({
                templateUrl: 'AppJs/advanced/user-profile/passChangeModal.html',
                backdrop: passChangeRequired ? 'static' : true,
                keyboard: !passChangeRequired,
                size: 'lg',
                controller: ['$scope', 'AuthService', 'toastr', '$uibModalInstance', function ($scope, Auth, toastr, $uibModalInstance) {
                    angular.extend($scope, {
                        password: {},
                        submitIfReady: submitIfReady,
                        changePassword: changePassword,
                        isChangingPass: false,
                        allowCancel: !passChangeRequired,
                        isLongEnough: isLongEnough,
                        hasDigits: hasDigits,
                        hasLower: hasLower,
                        hasUpper: hasUpper,
                        hasSpecial: hasSpecial,
                        isVerified: isVerified,
                        hasError: false,
                        hideError: false
                    });

                    $log.info("userCreds", userCreds);

                    if (userCreds)
                        $scope.password.oldPassword = userCreds.password;

                    function changePassword() {
                        $scope.isChangingPass = true;

                        $log.info("Changing Password...", userCreds);
                        return Auth
                            //.changePassword($scope.password.oldPassword, $scope.password.newPassword, userCreds ? userCreds.name : null)
                            .changePassword($scope.password.oldPassword, $scope.password.newPassword, userCreds ? userCreds.login : null)
                            .then(function (result) {

                                $log.info("result", result);
                                $scope.isChangingPass = false;

                                if (result.data.isOk === true) {
                                    toastr.success("Your password has been changed.");
                                    $uibModalInstance.close(userCreds ? { name: userCreds.login, password: $scope.password.newPassword } : true);
                                }
                                else {
                                    toastr.error("We're not sure what happened, but when we tried to change your password an error occurred. Consider trying again.");
                                    $scope.hasError = true;
                                }
                            });
                    }

                    function submitIfReady(e, isValid) {
                        e.preventDefault();
                        if (isValid)
                            changePassword();
                    }

                    function isLongEnough(val) {
                        return val && val.length >= 12;
                    }

                    function hasDigits(val) {
                        return /\d/.test(val);
                    }

                    function hasLower(val) {
                        return /[a-z]/.test(val);
                    }

                    function hasUpper(val) {
                        return /[A-Z]/.test(val);
                    }

                    function hasSpecial(val) {
                        return /[@!$%#]{1,}/.test(val);
                    }

                    function isVerified(val, val2) {
                        return val == val2;
                    }
                }]
            }).result;
        }

    }
})();;
(function () {
    'use strict';

    angular
      .module('app')
      .controller('UserProfileController', UserProfileController);

    UserProfileController.$inject = ['config', '$scope', '$rootScope', 'AuthService', 'UserPassChangeService', '$log', 'toastr', 'DataSetService', 'MenuService', 'AdminService'];

    function UserProfileController(config, $scope, $rootScope, Auth, PassChanger, $log, toastr, DataSets, MenuService, AdminService) {
        angular.extend($scope, {
            changePassword: changePassword,
            updateProfile: updateProfile,
            dataSets: [],
            selectedDataSet: null,
            updatingDataSet: false,
            password: {},
            user: Auth.details,
            Roles: [],
            menuLayouts: [],
            dataSetChanged: handleDataSetChanged,
            menuRoleChanged: handleMenuRoleChanged,
            menuLayoutId: 0,
            showChangePassButton: config.authMethod == "Forms",
            inArchiveDataset: false
        });

        activate();

        function activate() {
            $scope.dataSets = $rootScope.dataSets;
            $scope.selectedDataSet = $rootScope.dataSet;

            getRoles();


            if ($rootScope.menuData == undefined) {
               MenuService.GetMenuLayouts().then(function (result) {
                    MenuService.SetSelectedMenuLayout(Auth.details.menuLayoutId);
                    $scope.menuLayouts = $rootScope.menuData.menuLayouts;
                    $scope.selectedMenuLayout = $rootScope.menuData.selectedMenuLayout;
                   //MenuService.BuildMenu();
                    MenuService.BuildMenu($scope.user.roles);
                    MenuService.UpdateSideNav();
                });              
            }
            else
            {
                $scope.menuLayouts = $rootScope.menuData.menuLayouts;
                $scope.selectedMenuLayout = $rootScope.menuData.selectedMenuLayout;
            }
        }

        function updateProfile()
        {
            AdminService.updateMenuLayout($scope.user.userId, $scope.selectedMenuLayout.menuLayoutId)
            .then(function (data) {
                if (data.status == "Success") {
                    Auth.updateMenuLayout($scope.selectedMenuLayout.menuLayoutId);
                    $scope.selectedMenuLayout = $rootScope.menuData.selectedMenuLayout = _.find($rootScope.menuData.menuLayouts, function (m) { return m.menuLayoutId == $scope.selectedMenuLayout.menuLayoutId; });
                    toastr.success("Menu settings successfully updated!");
                    $rootScope.menuData.menuLayoutId == $scope.selectedMenuLayout.menuLayoutId;
                    //MenuService.BuildMenu();
                    MenuService.BuildMenu($scope.user.roles);
                    MenuService.UpdateSideNav();
                }
            });
        }

        function getRoles() {
            var data = $scope.user.roles;
                Auth.GetRoleFriendlyNames(data).then(function (result) {
                    $scope.Roles = result.data;
            });

        }       

        function changePassword() {
            if (config.authMethod == "Forms")
                PassChanger.openModal(false, $scope.user);
        }

        function handleDataSetChanged() {
            $scope.updatingDataSet = true;
            DataSets.save({ id: $scope.selectedDataSet.id }, {},
                function Success() {
                    $log.info("SUCCESS!");
                    $rootScope.dataSet.isUserChoice = false; // for consistency's sake, but not really needed

                    $rootScope.dataSet = $scope.selectedDataSet;
                    $rootScope.dataSet.isUserChoice = true;

                    $scope.updatingDataSet = false;

                    // rebuild the menu with the roles after dataset change
                    var returningToLive = ($scope.selectedDataSet.name.toUpperCase() === "LIVE" || $scope.selectedDataSet.id.toUpperCase() === "LIVE");
                    Auth.getUserRoleFormalNames(returningToLive).then(function (result) {
                        MenuService.BuildMenu(result.data);
                        MenuService.UpdateSideNav();                        
                    });
                    
                    if (returningToLive) {
                        $("#header-container").removeClass("archiveData");
                    }
                    else {
                        $("#header-container").addClass("archiveData");
                    }

                    toastr.success("Your dataset was updated successfully.");

                    

                    //window.location = "/advanced/index";
                    
                },
                function Failure() {
                    $log.info("FAILURE!");
                    toastr.error("The dataset you selected does not exist, please contact your administrator.");
                    $scope.selectedDataSet = $rootScope.dataSet;

                    $scope.updatingDataSet = false;
                });
        }

        function handleMenuRoleChanged() {

        }

    }


})();;
