/*Slider interface for price ranges, all adjoiners returned in one batch, debugged erasing with labels, erase indicator, fixed label toggle, removed 

max-length from advanced search*/

(function () {
    var secretEmptyKey = '[$empty$]';

    var app = angular.module('MobileWebLogistics', ['ui.router', 'ui.bootstrap', 'colorpicker.module', 'Routing', 'MWL', 'ngSanitize', 'naturalSort']);

    //If a parcel's image is missing from the img/parcels directory, replace it with the generic placeholder
    app.directive('errSrc', function () {
        return {
            link: function (scope, element, attrs) {
                element.bind('error', function () {
                    if (attrs.src != attrs.errSrc) {
                        attrs.$set('src', attrs.errSrc);
                    }
                });
            }
        }
    });
    //this is for toggle UI
    app.directive('bindHtmlCompile', ['$compile', function ($compile) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.$watch(function () {
                    return scope.$eval(attrs.bindHtmlCompile);
                }, function (value) {
                    element.html(value);
                    $compile(element.contents())(scope);
                });
            }

        };
    }]);

    app.directive('emptyTypeahead', function () {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, modelCtrl) {
                // this parser run before typeahead's parser
                modelCtrl.$parsers.unshift(function (inputValue) {
                    var value = (inputValue ? inputValue : secretEmptyKey); // replace empty string with secretEmptyKey to bypass typeahead-min-length check
                    modelCtrl.$viewValue = value; // this $viewValue must match the inputValue pass to typehead directive
                    return value;
                });

                // this parser run after typeahead's parser
                modelCtrl.$parsers.push(function (inputValue) {
                    return inputValue === secretEmptyKey ? '' : inputValue; // set the secretEmptyKey back to empty string
                });
            }
        }
    });
    app.controller('PopupInstanceController', ['$scope', '$modalInstance', '$modal', 'panelControl', //panelControl is the service in panelControl.js
        function ($scope, $modalInstance, $modal, panelControl) {
            $scope.closeModal = function () {
                $modalInstance.dismiss('cancel');
            };
            $scope.gotoCal1 = function () {
                $modalInstance.dismiss('cancel');
                panelControl.openM1($scope, $modal);
            };
            $scope.gotoCal2 = function () {
                $modalInstance.dismiss('cancel');
                panelControl.openM2($scope, $modal);
            };
        }
    ]);
    //this is for disclaimer
    app.controller('DisclaimerHelpController', ['$rootScope', '$scope', '$state', '$timeout', '$modal', '$location', '$http',
        function ($rootScope, $scope, $state, $timeout, $modal, $location, $http) {
            //==code for secureSite== *also add $rootScope above
            //window.sessionStorage.setItem('loginTry', 0);
            $.getJSON('js/local_config_mapServUrl.js', function (appConfig) {
                $scope.secureSite = appConfig['secureSite'];
                $scope.portalAuth = appConfig['portalAuth'];
                $scope.portalName = appConfig['portalName'];
                $scope.agsVersion = appConfig['agsVersion'];
                $rootScope.secureSite = $scope.secureSite;
                $rootScope.portalAuth = $scope.portalAuth;
                $rootScope.portalName = $scope.portalName;
                $rootScope.agsVersion = $scope.agsVersion;
                if (appConfig['isFeatureService'] == "true") {
                    $scope.isFeatureService = true;
                }
                else {
                    try {
                        $scope.baseUrl = appConfig['baseUrl'];
                    }
                    catch {
                        $scope.baseUrl = null;
                    }
                }

                if (appConfig['isAGOLHostedFeatureService'] == "true") {
                    $scope.isAGOLHostedFeatureService = true;
                }
                else {
                    $scope.isAGOLHostedFeatureService = false;
                }
                $rootScope.isAGOLHostedFeatureService = $scope.isAGOLHostedFeatureService;

                window.sessionStorage.setItem('secureSite', $scope.secureSite);
                if ($scope.secureSite == "true" && $rootScope.helpActive != "true") {
                    window.sessionStorage.setItem('secureSite', $scope.secureSite);
                    $rootScope.helpActive = "false";
                    $state.go('login');
                }
                //==end==
            });
            $.getJSON('js/local_config_splash.js', function (appConfig) {

                $scope.logo = appConfig['logo'];
                $scope.countyName = appConfig['countyName'];
                $scope.pageTitle = appConfig['pageTitle'];


                $scope.subSet1 = appConfig['subSet1'];
                $scope.subSet2 = appConfig['subSet2'];
                $scope.disclaimerAgree = appConfig['disclaimerAgree'];
                if ($scope.disclaimerAgree === undefined) {
                    $scope.disclaimerAgree = "I AGREE";
                }
                $scope.disclaimerTxt = appConfig['disclaimerTxt'];
                $scope.lastUpdated = appConfig['lastUpdated'];
                $scope.disclaimerContent = $scope.disclaimerTxt + $scope.lastUpdated;
                $scope.$apply();
                $(document).ready(function () {
                    document.title = $scope.pageTitle;
                });
            });
            $.getJSON('js/local_config_help.js', function (appConfig) {
                $scope.helpLogo = appConfig['helpLogo'];
                $scope.hyperCountyName = appConfig['hyperCountyName'];
                $scope.helpURL = appConfig['helpURL'];
                $scope.additionalHelpTxt = appConfig['additionalHelpTxt'];
                $scope.$apply();
            });
            $scope.showDisclaimer = function () {
                if ($("#disclaimerContainer").is(":visible")) {
                    // Hide 
                    $("#pullButton").animate({
                        bottom: '0px'
                    });
                    $("#disclaimerContainer").slideUp(400);
                } else {
                    // Show           
                    $("#pullButton").animate({
                        bottom: '50%'
                    });
                    $("#disclaimerContainer").slideDown(400);
                }
            };
            // set the redirected to true
            window.sessionStorage.setItem('redirected', true);

            //==code for secureSite== 
            $scope.loginWarningTxt = "Sorry, there have been more than maximum failed login attempts. The user has been locked out of the system for a minute. Try again later in new tab.";

            if (window.sessionStorage.getItem('loginTry') > 5) {
                $scope.loginWarning = $scope.loginWarningTxt;
                $("#username").prop('disabled', true);
                $("#password").prop('disabled', true);
                $("#loginBtn").prop('disabled', true);
            }
            $scope.login = function (username, password) {
                $scope.loginWarning = "";
                if (!window.sessionStorage.getItem('loginTry')) {
                    window.sessionStorage.setItem('loginTry', 0);
                }
                if (window.sessionStorage.getItem('loginTry') > 5) {
                    $scope.loginWarning = $scope.loginWarningTxt;
                    $("#username").prop('disabled', true);
                    $("#password").prop('disabled', true);
                    $("#loginBtn").prop('disabled', true);
                    //$scope.$apply();                        
                    return;
                }

                if ($scope.portalAuth == "true") {
                    var ajaxUrl = $scope.baseUrl.replace("arcgis", $scope.portalName) + "/sharing/rest/generateToken/";
                    var data = { request: "getToken", username: username, password: password, expiration: 4320, f: "json", referer: "requestip" };
                }
                else if ($scope.isAGOLHostedFeatureService) {
                    var ajaxUrl = "https://www.arcgis.com/sharing/rest/generateToken";
                    var data = { request: "getToken", username: username, password: password, expiration: 4320, f: "json", referer: "requestip" };
                }
                else {
                    var ajaxUrl = $scope.baseUrl + "tokens/";
                    var data = { request: "getToken", username: username, password: password, expiration: 4320, f: "json" };
                }
                $.ajax({
                    url: ajaxUrl,
                    type: "POST",
                    data: data,
                    contentType: "application/x-www-form-urlencoded",
                    dataType: "json",
                    success: function (token) {
                        //console.log(username.value);      
                        if (token.token) {
                            $scope.loginWarning = "";
                            $rootScope.tokenObj = token;
                            $rootScope.username = username;
                            $rootScope.token = token.token;
                            window.sessionStorage.setItem('username', $rootScope.username);
                            window.sessionStorage.setItem('esriToken', $rootScope.token);
                            // set the redirected to true
                            window.sessionStorage.setItem('redirected', true);
                            $state.go('mwl');
                        }
                        else {
                            //alert(token.error.message);                        
                            window.sessionStorage.setItem('loginTry', parseInt(window.sessionStorage.getItem('loginTry')) + 1);
                            $scope.loginWarning = token.error.details + "! " + token.error.message + ".";   // + window.sessionStorage.getItem('loginTry');
                            $scope.$apply();
                            return;
                        }
                    }       //end of success
                });
            }
            //==end==
        }
    ]);
    app.controller('ImageController', ['$scope', '$state', '$timeout', '$modal', '$location', '$http', 'wlFactory',
        function ($scope, $state, $timeout, $modal, $location, $http, wlFactory) {
            //$scope.parcelImages=wlFactory.getParcelImages($scope);
            //$scope.parcelImages=['n'];
            $scope.aaa = true;
        }
    ]);
    //core Angular app controller
    app.controller('IndexController', ['$rootScope', '$scope', '$scope', '$state', '$timeout', '$modal', '$location', '$http', 'createReport', 'mapTools', 'parcelSearch', 'searchResult', 'zoomTo', 'mapFunction', 'printMap', 'panelControl', 'localCustom', 'layersUI', 'layerEvent', 'wlFactory',
        function ($rootScope, $scope, $scope, $state, $timeout, $modal, $location, $http, createReport, mapTools, parcelSearch, searchResult, zoomTo, mapFunction, printMap, panelControl, localCustom, layersUI, layerEvent, wlFactory) {
            $.getJSON('js/local_config_main.js', function (appConfig) {
                var path = $location.path();
                var rawCoords = $location.search().location;
                var zoomLevel = $location.search().zoom;
                var parcelID = $location.search().parcelID;
                // handle if user goes to site/#/mwl with xy, zoom
                if ((rawCoords && zoomLevel || parcelID) && appConfig["redirectToDisclaimer"] == "true") {
                    window.sessionStorage.setItem('redirected', true);
                    window.sessionStorage.setItem('rawCoords', rawCoords);
                    window.sessionStorage.setItem('zoomLevel', zoomLevel);
                    window.sessionStorage.setItem('parcelID', parcelID);
                    window.location.href = window.location.pathname;
                }
                // handle if user goes to site/#/mwl with xy
                else if ((rawCoords || parcelID) && appConfig["redirectToDisclaimer"] == "true") {
                    window.sessionStorage.setItem('redirected', true);
                    window.sessionStorage.setItem('rawCoords', rawCoords);
                    window.sessionStorage.setItem('parcelID', parcelID);
                    window.location.href = window.location.pathname;
                }
                // handle if a user goes to site/#/mwl without xy, zoom
                else if (path && appConfig["redirectToDisclaimer"] == "true" && !window.sessionStorage.redirected) {
                    window.sessionStorage.setItem('redirected', true);
                    window.location.href = window.location.pathname;
                }
                // send to map
                else {
                    window.location.href = window.location.href;
                }
            });

            $.getJSON('js/local_config_mapServUrl.js', function (appConfig) {
                // set the core config to determine if the data source is in AGO (a feature service)
                // or a traditional map service typically client-hosted
                var gisServStrucJsonLink;
                if (appConfig['isFeatureService'] == "true") {
                    $scope.isFeatureService = true;
                    $scope.featureServUrl = appConfig["featureServUrl"];
                    $scope.printServiceUrl = appConfig["printServiceUrl"];
                    $scope.geometryServiceUrl = appConfig["geometryServiceUrl"];
                    gisServStrucJsonLink = $scope.featureServUrl + "layers?f=json";
                }
                else {
                    $scope.isFeatureService = false;
                    $scope.baseUrl = appConfig['baseUrl'];
                    $scope.mapServUrl = $scope.baseUrl + appConfig['mapServUrl'];
                    $scope.printServiceUrl = $scope.baseUrl + appConfig["printServiceUrl"];
                    $scope.geometryServiceUrl = $scope.baseUrl + appConfig["geometryServiceUrl"];
                    $scope.corsEnabledServersUrl = $scope.baseUrl.replace('/arcgis/', '');
                    $scope.featureServUrl = $scope.mapServUrl;
                    gisServStrucJsonLink = $scope.featureServUrl + "layers?f=json";
                }

                $scope.parcelLyrName = appConfig['parcelLyrName'];
                $scope.parcelLayerName = $scope.parcelLyrName.split(' ').join('_');
                $scope.localCustom = localCustom;

                //==code for secureSite== *also add $rootScope above
                if (window.sessionStorage.getItem('secureSite') == 'true' && window.sessionStorage.getItem('esriToken') == null) {
                    //alert("gotoDis");
                    $state.go('disclaimer');
                    return;
                }
                $rootScope.token = window.sessionStorage.getItem('esriToken');
                if ($rootScope.token != null) {
                    gisServStrucJsonLink += "&token=" + $rootScope.token;
                }

                //==============
                $.getJSON(gisServStrucJsonLink)
                    .done(function (data) {
                        //console.log(data.layers);   
                        //==code for secureSite==     
                        if (data.layers == undefined) { $state.go('disclaimer'); return; }
                        //==end==                                    
                        $scope.gisServStrucData = data;
                        $scope.gisServNumLayers = data.layers.length;   //num of layers in the service
                        for (var i = 0; i < $scope.gisServNumLayers; i++) { // data.layers.length
                            //console.log(data.layers[i].name);
                            if (data.layers[i].name == $scope.parcelLyrName && data.layers[i].type == 'Feature Layer') {
                                $scope.parcelLyrId = data.layers[i].id;
                                //console.log('parcelLyrId:'+$scope.parcelLyrId)
                                i = data.layers.length;
                            }
                        }

                        $scope.searchParcelLyrId = $scope.parcelLyrId;
                        //console.log('parcelLayerName:'+$scope.parcelLayerName);
                        //console.log('searchParcelLyrId:'+$scope.searchParcelLyrId);

                        $.getJSON('js/local_config_bookmarks.js', function (appConfig) {
                            $scope.bookmarks = appConfig['bookmarks'];
                        });
                        $.getJSON('js/local_config_identify.js', function (appConfig) {
                            $scope.bubbleInfoField = appConfig["bubbleInfoField"];
                            $scope.ptBubbleInfoField = appConfig["ptBubbleInfoField"];

                            $scope.bubbleInfoNum = $scope.bubbleInfoField.length;
                            try {
                                $scope.bubbleBtnTxt = appConfig["bubbleBtnTxt"].split(",");
                            } catch (err) {
                                $scope.bubbleBtnTxt = ['Show Adjoiners', 'More Details']; //default btnTxt
                            }

                        });
                        $.getJSON('js/local_config_main.js', function (appConfig) {

                            // setting this to "true" will enable the parcel highlight to remain when popup is dismissed
                            $scope.keepHighlightOnHide = appConfig['keepHighlightOnHide'];

                            // setting this to "true" will enable the parcel map image in the pdf report
                            $scope.enableCreateReportParcelMap = appConfig['enableCreateReportParcelMap'];
                            $scope.baseColor = appConfig['baseColor'];
                            $scope.navLogo = appConfig['navLogo'];
                            $scope.navSubSet1 = appConfig['navSubSet1'];
                            $scope.navSubSet2 = appConfig['navSubSet2'];
                            $scope.navSubSetLink1 = appConfig['navSubSetLink1'];
                            $scope.navSubSetLink2 = appConfig['navSubSetLink2'];
                            $scope.customBanner = appConfig['customBanner'];

                            $scope.lViewBgTxt = appConfig['lViewBgTxt'];
                            $scope.pageTitle = appConfig['pageTitle'];
                            $(document).ready(function () {
                                document.title = $scope.pageTitle;
                                try {
                                    if ($scope.customBanner.length > 1) {
                                        console.log($scope.customBanner);
                                        $("#govName").append($scope.customBanner);
                                    }
                                } catch (err) {

                                }

                            });
                            $scope.thumbnailUrl = appConfig["thumbnailUrl"];
                            $scope.parcelUrl = $scope.thumbnailUrl.replace("Thumbnails", "Parcels");

                            // These variables were deleted to remove requests to non-existent parcel images
                            // Assumes the thumbnailUrl property in local_config_main.js is set to an empty string
                            if ($scope.thumbnailUrl == "") {
                                delete $scope.thumbnailUrl;
                                delete $scope.parcelUrl;
                            };

                            $scope.bookmarkMarkerImage = appConfig['bookmarkMarkerImage'];
                            $scope.pdfHeaderImage = appConfig['pdfHeaderImage'];

                            $scope.pdfHeaderTxt1 = appConfig['pdfHeaderTxt1'];
                            $scope.pdfHeaderTxt2 = appConfig['pdfHeaderTxt2'];
                            $scope.customPdfReporte = appConfig['customPdfReporte'];
                            $scope.combinedTypeAhead = appConfig['combinedTypeAhead'];


                            $scope.numOfTable = parseInt(appConfig['numOfTable']);
                            $scope.numOfDefQueryVar = appConfig['numOfDefQueryVar'];
                            $scope.numOfAdvQueryVar = appConfig['numOfAdvQueryVar'];
                            //console.log($scope.numOfTable);
                            $scope.tableArray = [];
                            for (var i = 1; i < $scope.numOfTable + 1; i++) {
                                $scope.tableArray.push(i);
                            }
                            //console.log($scope.tableArray);
                            $scope.draggableParcelIdentify = appConfig["draggableParcelIdentify"];
                            $scope.multipleParcelIdentify = appConfig["multipleParcelIdentify"];
                            $scope.identifyOthers = appConfig["identifyOthers"];
                            $scope.streetView = appConfig["streetView"];
                            $scope.eagleView = appConfig["eagleView"];
                            $scope.isCustomEagleView = appConfig["isCustomEagleView"];
                            $scope.searchNearby = appConfig["searchNearby"];
                            $scope.directAdvSearch = appConfig["directAdvSearch"];
                            $scope.qtipEffect = appConfig["qtipEffect"];
                            try {
                                localCustom.initQtip($scope);
                            } catch (err) {
                            }
                            $scope.swipeTool = appConfig["swipeTool"];
                            $scope.swipeStyleOptions = appConfig["swipeStyleOptions"];
                            if ($scope.swipeStyleOptions === undefined) {
                                $scope.swipeStyleOptions = ["Vertical", "Horizontal", "Scope"];
                            }
                            else {
                                $scope.swipeStyleOptions = appConfig["swipeStyleOptions"].split(",");
                            }
                            // $scope.selectSwipeStyleModel = $scope.swipeStyleOptions[0];
                            $scope.gotoXY = appConfig["gotoXY"];
                            $scope.selectByGraphic = appConfig["selectByGraphic"];
                            $scope.mapResults = appConfig["mapResults"];
                            $scope.mapMyResults = appConfig["mapMyResults"];
                            $scope.propertyImg = appConfig["propertyImg"];
                            $scope.customImgName = appConfig["customImgName"];
                            $scope.JPG = appConfig["JPG"];
                            $scope.customBasemap = appConfig["customBasemap"];
                            $scope.DrawToolsTxt = appConfig["DrawToolsTxt"];
                            try {
                                var temp = $scope.DrawToolsTxt.length;
                            } catch (err) {
                                $scope.DrawToolsTxt = 'Draw Tools';
                            }
                            if ($scope.DrawToolsTxt == 'Draw & Measure') {
                                $("#mapDropdowns").addClass('moveLeft');
                                $("#layerSelect").addClass('moveRight');
                            }
                            $scope.customRelatedFld = appConfig["customRelatedFld"];
                            $scope.customReportLink = appConfig["customReportLink"];

                            $scope.customDefSearchBar = appConfig["customDefSearchBar"];
                            $scope.customAdvSearchBar = appConfig["customAdvSearchBar"];

                            $scope.searchPriceMin = parseInt(appConfig["searchPriceMin"]);
                            $scope.searchPriceMax = parseInt(appConfig["searchPriceMax"]);
                            if (isNaN($scope.searchPriceMin)) {
                                //console.log('default');
                                $scope.searchPriceMin = parseInt('0');
                                $scope.searchPriceMax = parseInt('10000000');
                            }

                            $scope.noReport = appConfig["noReport"];
                            if ($scope.noReport == 'true') {
                                $("#viewParcelDetails").addClass('hideOption');
                            }
                            $scope.multipleReportImages = appConfig["multipleReportImages"];
                            try {
                                $scope.sumQueryResultFld = appConfig["sumQueryResultFld"].split(",");
                            } catch (err) {
                                $scope.sumQueryResultFld = [];
                            }
                            //console.log($scope.sumQueryResultFld);
                            $scope.searchBtnTxt = 'List Results';
                            if ($scope.mapResults == "false") {
                                $scope.searchBtnTxt = 'Search';
                            }

                            $scope.multipleImages = appConfig["multipleImages"];
                            $scope.multipleCoordinateDisplay = appConfig["multipleCoordinateDisplay"];
                            $scope.drawPoint = appConfig["drawPoint"];

                            $scope.downloadResults = appConfig["downloadResults"];
                            $scope.clearResults = appConfig["clearResults"];
                            $scope.clearAdjResults = appConfig["clearAdjResults"];
                            $scope.dynamicUnit = appConfig["dynamicUnit"].split(",");
                            $scope.isDynamicUnit = $scope.dynamicUnit[0];
                            $scope.lbBtns = appConfig["lbBtns"];

                            $scope.manualPrintScaleText = appConfig["manualPrintScaleText"];
                            try {
                                var temp = $scope.manualPrintScaleText.length;
                            } catch (err) {
                                $scope.manualPrintScaleText = "Printable Area";
                            }
                            try {
                                $scope.manualPrintScale = appConfig["manualPrintScale"];

                            } catch (err) {
                                $scope.manualPrintScale = "false";
                            }

                            $scope.showPrintLegend = appConfig["showPrintLegend"];

                            try {
                                var temp = $scope.showPrintLegend.length;
                            } catch (err) {
                                $scope.showPrintLegend = '';
                            }

                            try {
                                $scope.setIdentifyGeomToSelectedParcel = appConfig["setIdentifyGeomToSelectedParcel"];
                            }
                            catch (err) {
                                $scope.setIdentifyGeomToSelectedParcel = "false";
                            }
                            //Include whichever field names in these arrays that you would like formatted when they're received from the map service
                            /*$scope.currencyFields = appConfig["currencyFields"].split(",");
                            $scope.dateFields = appConfig["dateFields"].split(",");
                            $scope.numberFields = appConfig["numberFields"].split(",");
                            $scope.firstCapFields = appConfig["firstCapFields"].split(",");
                            $scope.allCapFields = appConfig["allCapFields"].split(",");
                            $scope.noNaFields = appConfig["noNaFields"].split(",");
                            $scope.replaceField = appConfig["replaceField"];
                            try{
                                var temp = $scope.replaceField.length;
                            }
                            catch(err){
                                $scope.replaceField=[];
                            }*/
                            $scope.excludeLayers = appConfig["excludeLayers"].split(",");
                            try {
                                $scope.customSearchOptions1 = appConfig["customSearchOptions1"].split(",");
                            } catch (err) {
                                $scope.customSearchOptions1 = [];
                            }

                            try {
                                $scope.customSearchOptions2 = appConfig["customSearchOptions2"].split(",");
                            } catch (err) {
                                $scope.customSearchOptions2 = [];
                            }

                            try {
                                $scope.customSearchOptions3 = appConfig["customSearchOptions3"].split(",");
                            } catch (err) {
                                $scope.customSearchOptions3 = [];
                            }

                            $scope.nArrow = appConfig["nArrow"];
                            $scope.sliderStyle = appConfig["sliderStyle"];
                            if ($scope.sliderStyle != 'large') {
                                $scope.sliderStyle = 'small'
                            }
                            try {
                                $scope.mSelParcelSymbolLine = appConfig["mSelParcelSymbolLine"].split(",");
                                $scope.mSelParcelSymbolFill = appConfig["mSelParcelSymbolFill"].split(",");
                                $scope.mSelPointSymbolLine = appConfig["mSelPointSymbolLine"].split(",");
                                $scope.mSelPointSymbolColor = appConfig["mSelPointSymbolColor"].split(",");
                                $scope.mSelPointSymbolSize = appConfig["mSelPointSymbolSize"];
                            } catch (err) {
                                $scope.mSelParcelSymbolLine = ["1", "255", "255", "1"];
                                $scope.mSelParcelSymbolFill = ["255", "255", "0", "0.2"];
                                $scope.mSelPointSymbolLine = ["1", "255", "255", "1"];
                                $scope.mSelPointSymbolColor = ["255", "255", "0", "0.2"];
                                $scope.mSelPointSymbolSize = 10;
                            }
                            try {
                                $scope.selParcelSymbolLine = appConfig["selParcelSymbolLine"].split(",");
                                $scope.selParcelSymbolFill = appConfig["selParcelSymbolFill"].split(",");
                            } catch (err) {
                                $scope.selParcelSymbolLine = ["1", "105", "202", "3"];
                                $scope.selParcelSymbolFill = ["255", "0", "0", "0"];
                            }
                            $scope.pdfBtnTxt = appConfig["pdfBtnTxt"];
                            $scope.csvBtnTxt = appConfig["csvBtnTxt"];

                            try { // to check if pdfBtnTxt is defined
                                var temp = $scope.pdfBtnTxt.length;
                            } catch (err) {
                                $scope.pdfBtnTxt = "Download PDF";
                            }
                            try { // to check if csvBtnTxt is defined
                                var temp = $scope.csvBtnTxt.length;
                            } catch (err) {
                                $scope.csvBtnTxt = "Download CSV";
                            }
                            try {
                                $scope.customReportTblName = appConfig["customReportTblName"];
                            } catch (err) {
                                console.log("noCustom");
                            }
                            $scope.countPdfPage = appConfig["countPdfPage"];
                            try { // to check if countPdfPage is defined
                                var temp = $scope.countPdfPage.length;
                            } catch (err) { //if countPdfPage is not defined
                                $scope.countPdfPage = 'false';
                            }

                            $scope.$apply();

                            $scope.initLayerIdsArray = new Array();
                            $scope.totalLayerCt = $scope.gisServStrucData.layers.length;
                            for (var i = 0; i < $scope.gisServStrucData.layers.length; i++) { // data.layers.length
                                var lnametxt = $scope.gisServStrucData.layers[i].name;
                                //var lname=lnametxt.split(' ').join('_').replace('/','').replace('&','and').replace('(','_').replace(')','').replace(/'/g, "");;

                                //capture the layer id from the service instead of the loop, this allows publishers to set their own unique ids in the map service if needed
                                var lid = $scope.gisServStrucData.layers[i].id;
                                // var lid=i;
                                var defaultVisibility = $scope.gisServStrucData.layers[i].defaultVisibility;
                                if ($scope.gisServStrucData.layers[i].type == "Feature Layer" || $scope.gisServStrucData.layers[i].type == "Annotation Layer" || $scope.gisServStrucData.layers[i].type == "Annotation SubLayer") {
                                    //excludeLayers
                                    var exLayer = "No";
                                    if ($scope.excludeLayers.length > 0) {
                                        for (var l = 0; l < $scope.excludeLayers.length; l++) {
                                            if ($scope.excludeLayers[l] == lnametxt) {
                                                exLayer = "Yes";
                                                l = $scope.initLayers.length; //to exit for loop
                                            }
                                        }
                                    }
                                    if (exLayer == "No") {
                                        if (defaultVisibility == true) {
                                            if ($scope.gisServStrucData.layers[i].type != "Annotation Layer") {
                                                if (lnametxt != $scope.parcelLyrName) { //parcel layer's original name in the map service
                                                    $scope.initLayerIdsArray.push(lid);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }); //end of getJSON('js/local_config_main.js'
                        $scope.pointTool = {};
                        $scope.pointTool.size = 12;
                        $scope.pointTool.color = "0000ff";
                        $scope.lineTool = {};
                        $scope.lineTool.thickness = 1;
                        $scope.lineTool.color = "FFFFFF";
                        $scope.shapeTool = {};
                        $scope.shapeTool.thickness = 1;
                        $scope.shapeTool.fillOpacity = 50;
                        $scope.shapeTool.color = "FFFFFF";
                        $scope.textTool = {};
                        $scope.textTool.size = 12;
                        $scope.baseMapTransparency = 100;
                        $scope.showLabels = true;
                        $scope.lastBufferDistance = null;
                        $scope.lastBufferUnit = "Feet";
                        $scope.headerData = "";
                        require([
                            "esri/map",
                            // "dojo/_base/xhr",
                            // "dojo/_base/array",
                            // "dojo/_base/unload",
                            "dojo/cookie",
                            "dojo/keys",
                            "dojo/dom-construct",
                            // "dojo/number",
                            "dojo/dom",
                            "dojo/on",
                            "dojo/dom-style",
                            "dojo/dnd/Moveable",
                            "dojo/query",
                            "dojo/dom-class",
                            "dojo/promise/all",
                            "esri/dijit/BasemapGallery",
                            "esri/dijit/LayerSwipe",
                            "esri/layers/ArcGISTiledMapServiceLayer",
                            "esri/layers/VectorTileLayer",
                            // "esri/arcgis/utils",
                            "esri/dijit/Print",
                            "esri/tasks/PrintTemplate",
                            "esri/tasks/RelationshipQuery",
                            "esri/geometry/webMercatorUtils",
                            "esri/graphicsUtils",
                            // "esri/layers/WMSLayer",
                            // "esri/layers/WMSLayerInfo",
                            "esri/layers/ArcGISDynamicMapServiceLayer",
                            "esri/layers/ImageParameters",
                            "esri/layers/FeatureLayer",
                            "esri/symbols/SimpleFillSymbol",
                            "esri/symbols/SimpleLineSymbol",
                            "esri/symbols/SimpleMarkerSymbol",
                            "esri/symbols/PictureMarkerSymbol",
                            "esri/symbols/Font",
                            "esri/symbols/TextSymbol",
                            "esri/layers/GraphicsLayer",
                            "esri/layers/LabelLayer",
                            // "esri/layers/LabelClass",
                            // "esri/layers/LayerDrawingOptions",
                            // "esri/layers/LabelClass",
                            "esri/renderers/SimpleRenderer",
                            "esri/renderers/UniqueValueRenderer",
                            "esri/toolbars/draw",
                            "esri/graphic",
                            // "esri/geometry/Geometry",
                            // "esri/geometry/Extent",
                            "esri/geometry/Point",
                            "esri/geometry/Polyline",
                            "esri/geometry/Polygon",
                            "esri/geometry/ScreenPoint",
                            "esri/SpatialReference",
                            "esri/geometry/normalizeUtils",
                            "esri/geometry/scaleUtils",
                            "esri/geometry/projection",
                            "esri/tasks/GeometryService",
                            "esri/tasks/BufferParameters",
                            "esri/tasks/LengthsParameters",
                            "esri/tasks/AreasAndLengthsParameters",
                            "esri/tasks/PrintTask",
                            "esri/tasks/IdentifyTask",
                            "esri/tasks/IdentifyParameters",
                            "esri/dijit/Popup",
                            "esri/toolbars/navigation",
                            "esri/lang",
                            // "esri/TimeExtent",
                            "esri/Color",
                            "esri/tasks/query",
                            "esri/tasks/QueryTask",
                            // "esri/tasks/geometry",
                            "dijit/TooltipDialog",
                            "dijit/popup",
                            "esri/dijit/LocateButton",
                            "esri/dijit/HomeButton",
                            "esri/dijit/BasemapToggle",
                            "esri/dijit/Scalebar",
                            "esri/dijit/OverviewMap",
                            "esri/SnappingManager",
                            "esri/InfoTemplate",
                            "esri/config",
                            "esri/sniff",
                            "esri/IdentityManager",
                            "esri/tasks/LegendLayer",
                            "dojox/gfx",
                            "esri/symbols/jsonUtils",
                            "dijit/form/Button",
                            "dijit/WidgetSet",
                            "dojo/domReady!"
                        ], function (
                            Map,
                            // xhr,
                            // arrayUtils,
                            // baseUnload,
                            cookie,
                            keys,
                            domConstruct,
                            // number,
                            dom,
                            on,
                            domStyle,
                            dojoMoveable,
                            dojoQuery,
                            domClass,
                            dojoAll,
                            BasemapGallery,
                            LayerSwipe,
                            ArcGISTiledMapServiceLayer,
                            VectorTileLayer,
                            // utils,
                            Print,
                            PrintTemplate,
                            RelationshipQuery,
                            webMercatorUtils,
                            graphicsUtils,
                            // WMSLayer,
                            // WMSLayerInfo,
                            ArcGISDynamicMapServiceLayer,
                            ImageParameters,
                            FeatureLayer,
                            SimpleFillSymbol,
                            SimpleLineSymbol,
                            SimpleMarkerSymbol,
                            PictureMarkerSymbol,
                            Font,
                            TextSymbol,
                            GraphicsLayer,
                            FeatureLabelLayer,
                            // FeatureLabelClass,
                            // LayerDrawingOptions,
                            // LabelClass,
                            SimpleRenderer,
                            UniqueValueRenderer,
                            Draw,
                            Graphic,
                            // Geometry,
                            // Extent,
                            Point,
                            Polyline,
                            Polygon,
                            ScreenPoint,
                            SpatialReference,
                            normalizeUtils,
                            scaleUtils,
                            projection,
                            GeometryService,
                            BufferParameters,
                            LengthsParameters,
                            AreasAndLengthsParameters,
                            PrintTask,
                            IdentifyTask,
                            IdentifyParameters,
                            esriPopup,
                            Navigation,
                            esriLang,
                            // TimeExtent,
                            Color,
                            Query,
                            QueryTask,
                            // geometry,
                            TooltipDialog,
                            dijitPopup,
                            LocateButton,
                            HomeButton,
                            BasemapToggle,
                            Scalebar,
                            OverviewMap,
                            SnappingManager,
                            InfoTemplate,
                            esriConfig,
                            has,
                            esriId,
                            LegendLayer,
                            gfx,
                            symbolJsonUtils
                        ) {
                            var WMSLayerUrl, queryTaskTouchesUrl, queryGeomUrl, initLayerIds, labelArray, initx, inity, initzoom, districtOptions, gfx, symbolJsonUtils;
                            //==code for secureSite== *also add $rootScope above
                            if ($scope.secureSite == "true") {
                                var agsToken = "esri_jsapi_id_manager_data"; // cookie/local storage name
                                // var hostname = $scope.baseUrl.replace('/arcgis/',''); 
                                if ($scope.baseUrl) {
                                    var hostname = $scope.baseUrl.replace('/arcgis/', '');
                                }
                                else if ($scope.isAGOLHostedFeatureService) {
                                    var hostname = "https://www.arcgis.com";
                                }
                                if ($scope.mapServUrl) {
                                    serviceUrl = $scope.mapServUrl;
                                }
                                else {
                                    serviceUrl = $scope.featureServUrl;
                                }

                                var timeout = 480; //minutes
                                var now = +(new Date());    //2880000 milisec=8hr
                                var expires = now + (timeout * 60000); //480*60000 = 2880000 milisec = 8hr
                                var imObject1 = {
                                    'serverInfos': [{
                                        'server': hostname + '/arcgis',
                                        'tokenServiceUrl': hostname + '/arcgis/tokens/',
                                        'adminTokenServiceUrl': hostname + '/arcgis/admin/generateToken',
                                        'shortLivedTokenValidity': 480,     //minutes
                                        'hasServer': true
                                    }],
                                    'oAuthInfos': [],
                                    'credentials': [{
                                        'userId': window.sessionStorage.getItem('username'),
                                        'server': hostname + '/arcgis',
                                        'token': window.sessionStorage.getItem('esriToken'),
                                        'expires': expires,
                                        'validity': 480,
                                        'ssl': true,
                                        'creationTime': new Date().getTime(),
                                        'scope': 'server',
                                        'resources': [
                                            $scope.geometryServiceUrl,
                                            $scope.printServiceUrl,
                                            serviceUrl
                                        ]
                                    }]
                                }

                                if ($scope.portalAuth == "true") {
                                    // By uncommenting the updates to serverInfos["server"] and credentials["server"]
                                    // the user is prompt again when the map loads to enter credentials
                                    // The IdentityManager object is not called again and it does not seem necessary to update

                                    var serverInfos = imObject1["serverInfos"][0];
                                    // serverInfos["server"] = hostname + '/' + $scope.portalName;
                                    serverInfos["tokenServiceUrl"] = hostname + '/' + $scope.portalName + '/sharing/rest/generateToken';
                                    serverInfos["adminTokenServiceUrl"] = hostname + '/' + $scope.portalName + '/sharing/rest/generateToken';
                                    if ($scope.agsVersion) {
                                        serverInfos["currentVersion"] = $scope.agsVersion;
                                    }

                                    // var credentials = imObject1["credentials"][0];
                                    // credentials["server"] = hostname + '/' + $scope.portalName;
                                }
                                else if ($scope.isAGOLHostedFeatureService) {
                                    if ($rootScope.token) {
                                        // we just need the serverCredential
                                        // there were conflicts with registerToken and then adding in public AGOL basemaps to the BasemapGallery
                                        // var tokenObj = $rootScope.tokenObj;
                                        // tokenObj["server"] = "https://www.arcgis.com/sharing/rest";
                                        // tokenObj["userId"] = window.sessionStorage.username;
                                        // esriId.registerToken(tokenObj);
                                        // esriId.credentials[0]["resources"].push("https://www.arcgis.com/sharing/rest/portals/self");
                                        // esriId.credentials[0]["resources"].push("https://www.arcgis.com/sharing/rest");
                                        // esriId.credentials[0]["resources"].push("http://www.arcgis.com/sharing/rest");
                                        // esriId.credentials[0]["resources"].push("https://server.arcgisonline.com");
                                        // esriId.credentials[0]["resources"].push("https://server.arcgisonline.com");

                                        var serverCredential = {
                                            "userId": window.sessionStorage.username,
                                            "server": $scope.featureServUrl.split("/rest/services")[0],
                                            "token": $rootScope.token,
                                            "expires": $rootScope.tokenObj.expires,
                                            "scope": "server",
                                            "ssl": true,
                                            "resources": [
                                                $scope.featureServUrl
                                            ]
                                        }
                                        // for (i=0; i < $scope.gisServStrucData.layers.length; i++) {
                                        //     serverCredential["resources"].push($scope.featureServUrl + $scope.gisServStrucData.layers[i].id);
                                        //     serverCredential["resources"].push($scope.featureServUrl + $scope.gisServStrucData.layers[i].id + "/query");
                                        // }
                                        // for (j=0; i < $scope.gisServStrucData.tables.length; j++) {
                                        //     serverCredential["resources"].push($scope.featureServUrl + $scope.gisServStrucData.tables[j].id);
                                        //     serverCredential["resources"].push($scope.featureServUrl + $scope.gisServStrucData.tables[j].id + "/query");
                                        // }
                                        esriId.credentials.push(serverCredential);
                                    }
                                }
                                $scope.supports_local_storage = function () {
                                    try {
                                        return "localStorage" in window && window["localStorage"] !== null;
                                    } catch (e) {
                                        return false;
                                    }
                                }
                                $scope.storeCredentials = function () {
                                    // make sure there are some credentials to persist
                                    if (esriId.credentials.length === 0) {
                                        return;
                                    }

                                    // serialize the ID manager state to a string
                                    var idString = JSON.stringify(esriId.toJson());
                                    // store it client side
                                    if ($scope.supports_local_storage()) {
                                        // use local storage
                                        window.localStorage.setItem(agsToken, idString);
                                        // console.log("wrote to local storage");
                                    }
                                    else {
                                        // use a cookie
                                        cookie(agsToken, idString, { expires: 1 });
                                        // console.log("wrote a cookie :-/");
                                    }
                                }
                                //$scope.loadCredentials();
                                if (esriId.credentials.length == 0 && window.sessionStorage.getItem('username') != null) {
                                    esriId.initialize(imObject1);
                                    $scope.storeCredentials();
                                }
                            }
                            //==end==
                            $scope.SimpleRenderer = SimpleRenderer;
                            $scope.ScreenPoint = ScreenPoint;
                            $scope.webMercatorUtils = webMercatorUtils;
                            $scope.graphicsUtils = graphicsUtils;
                            $scope.BasemapGallery = BasemapGallery;
                            $scope.LayerSwipe = LayerSwipe;
                            $scope.swipeOn = false;
                            $scope.ArcGISDynamicMapServiceLayer = ArcGISDynamicMapServiceLayer;
                            $scope.ArcGISTiledMapServiceLayer = ArcGISTiledMapServiceLayer;
                            $scope.VectorTileLayer = VectorTileLayer;
                            $scope.scaleUtils = scaleUtils;
                            $scope.projection = projection;
                            $scope.PrintTask = PrintTask;
                            $scope.RelationshipQuery = RelationshipQuery;
                            $scope.PrintTemplate = PrintTemplate;
                            $scope.IdentifyTask = IdentifyTask;
                            $scope.IdentifyParameters = IdentifyParameters;
                            $scope.esriPopup = esriPopup;
                            // $scope.arrayUtils = arrayUtils;
                            $scope.InfoTemplate = InfoTemplate;
                            $scope.Draw = Draw;
                            $scope.Font = Font;
                            $scope.TextSymbol = TextSymbol;
                            $scope.SimpleLineSymbol = SimpleLineSymbol;
                            $scope.SimpleMarkerSymbol = SimpleMarkerSymbol;
                            $scope.PictureMarkerSymbol = PictureMarkerSymbol;
                            $scope.FeatureLayer = FeatureLayer;
                            $scope.SimpleFillSymbol = SimpleFillSymbol;
                            $scope.Color = Color;
                            $scope.LengthsParameters = LengthsParameters;
                            $scope.AreasAndLengthsParameters = AreasAndLengthsParameters;
                            $scope.normalizeUtils = normalizeUtils;
                            $scope.SpatialReference = SpatialReference;
                            $scope.BufferParameters = BufferParameters;
                            $scope.Query = Query;
                            $scope.QueryTask = QueryTask;
                            $scope.GeometryService = GeometryService;
                            $scope.Point = Point;
                            $scope.Polyline = Polyline;
                            $scope.Polygon = Polygon;
                            $scope.Graphic = Graphic;
                            $scope.esriLang = esriLang;
                            $scope.domStyle = domStyle;
                            $scope.dojoAll = dojoAll;
                            $scope.dijitPopup = dijitPopup;
                            $scope.HomeButton = HomeButton;
                            $scope.OverviewMap = OverviewMap;
                            $scope.esriConfig = esriConfig;
                            $scope.legendLayer = LegendLayer;
                            $scope.gfx = gfx;
                            $scope.symbolJsonUtils = symbolJsonUtils;
                            $scope.domConstruct = domConstruct;
                            $scope.esriId = esriId;
                            $scope.resizeLbBtns = function () { //basemapGalleryBtn and Google Street View Btn
                                if (window.innerWidth > 650) {
                                    $("#basemapGalleryButton").removeClass("basemapGalleryButtonSm");
                                    $("#basemapGalleryButton").addClass("basemapGalleryButtonLg");
                                    $("#bmapBtnTxt").text(" Basemaps");
                                    $("#pictoButton").removeClass("pictoButtonSm");
                                    $("#pictoButton").addClass("pictoButtonLg");
                                    $("#eagleViewBtnTxt").text("Eagle view");
                                    $("#GSButton").removeClass("GSButtonSm");
                                    $("#GSButton").addClass("GSButtonLg");
                                    $("#sviewBtnTxt").text(" Street view");
                                } else {
                                    $("#basemapGalleryButton").removeClass("basemapGalleryButtonLg");
                                    $("#basemapGalleryButton").addClass("basemapGalleryButtonSm");
                                    $("#bmapBtnTxt").text("");
                                    $("#pictoButton").removeClass("pictoButtonLg");
                                    $("#pictoButton").addClass("pictoButtonSm");
                                    $("#eagleViewBtnTxt").text("");
                                    $("#GSButton").removeClass("GSButtonLg");
                                    $("#GSButton").addClass("GSButtonSm");
                                    $("#sviewBtnTxt").text("");
                                }
                            }
                            //initial btn resize
                            switch ($scope.lbBtns) {
                                case 'sm':
                                    //code block
                                    break;
                                case 'lg':
                                    $("#basemapGalleryButton").removeClass("basemapGalleryButtonSm");
                                    $("#basemapGalleryButton").addClass("basemapGalleryButtonLg");
                                    $("#bmapBtnTxt").text(" Basemaps");
                                    $("#pictoButton").removeClass("pictoButtonSm");
                                    $("#pictoButton").addClass("pictoButtonLg");
                                    $("#eagleViewBtnTxt").text(" Eagle view");
                                    $("#GSButton").removeClass("GSButtonSm");
                                    $("#GSButton").addClass("GSButtonLg");
                                    $("#sviewBtnTxt").text(" Street view");
                                    break;
                                case 'dynamic':
                                    $scope.resizeLbBtns();
                                    break;
                            }
                            $.getJSON('js/local_config_service.js', function (appConfig) {

                                //$scope.featureServUrl=appConfig["featureServUrl"];
                                //WMSLayerUrl=appConfig["WMSLayerUrl"];
                                WMSLayerUrl = $scope.featureServUrl.substring(0, $scope.featureServUrl.length - 1);
                                //printServiceUrl=appConfig["printServiceUrl"];          
                                //$scope.searchParcelLyrId=appConfig["searchAheadUrl"];
                                $scope.searchAheadUrl = $scope.featureServUrl + $scope.searchParcelLyrId;
                                $scope.searchPtLyrId = appConfig["searchPtUrl"];

                                $scope.searchPtUrl = $scope.featureServUrl + $scope.searchPtLyrId;
                                queryTaskTouchesUrl = $scope.featureServUrl + $scope.searchParcelLyrId;
                                searchAheadAddUrl = $scope.featureServUrl + $scope.searchParcelLyrId;
                                queryGeomUrl = $scope.featureServUrl + $scope.searchParcelLyrId;
                                $scope.queryTaskUrl = $scope.featureServUrl + $scope.searchParcelLyrId;

                                //proxyUrl=appConfig["proxyUrl"];
                                //$scope.geometryServiceUrl=appConfig["geometryServiceUrl"];
                                //esriGeometryServiceUrl=appConfig["esriGeometryServiceUrl"];
                                //corsEnabledServersUrl=appConfig["corsEnabledServersUrl"];
                                //$scope.parcelLayerName = appConfig["parcelLayerName"];            
                                $scope.initLayers = appConfig["initLayers"].split(",");
                                initLayerIds = appConfig["initLayerIds"].split(",");

                                //$scope.initLayers = $scope.initLayerNamesArray;
                                //initLayerIds = $scope.initLayerIdsArray;
                                $scope.parcelOID = appConfig["parcelOID"];
                                $scope.parcelUid = appConfig["parcelUid"];
                                $scope.addrPtUid = appConfig["addrPtUid"];
                                $scope.addrPtLyrName = appConfig["addrPtLyrName"];

                                $scope.imageUid = appConfig["imageUid"];
                                $scope.reportId = appConfig["reportId"];
                                try {
                                    $scope.parcelpdfID = appConfig["parcelpdfID"].split(",");
                                } catch (err) {
                                    $scope.parcelpdfID = [];
                                    $scope.parcelpdfID[0] = ' ';
                                    $scope.parcelpdfID[1] = ' ';
                                }
                                try {
                                    $scope.initOpacity = appConfig["initOpacity"];
                                }
                                catch (err) {
                                    $scope.initOpacity = 100;
                                }

                                $scope.saleDateFld = appConfig["saleDateFld"];
                                $scope.salePriceFld = appConfig["salePriceFld"];
                                $scope.dataWkid = appConfig["dataWkid"];
                                try {
                                    var temp = $scope.dataWkid.length;
                                } catch (err) {
                                    $scope.dataWkid = '102100';
                                }
                                $scope.baseMapOrder = appConfig["baseMapOrder"].split(",");
                                $scope.removeBaseMaps = appConfig["removeBaseMaps"].split(",");
                                //$scope.baseMapTitles = JSON.parse("[" + appConfig["baseMapTitles"] + "]");
                                $scope.baseMapTitles = appConfig["baseMapTitles"];

                                $scope.minZoom = appConfig["minZoom"];
                                $scope.maxZoom = appConfig["maxZoom"];
                                $scope.initZoom = appConfig["initzoom"];

                                $scope.defaultBasemap = appConfig["defaultBasemap"];
                                labelArray = appConfig["labelArray"];
                                $scope.addToSearchAheadOutFields = appConfig["addToSearchAheadOutFields"].split(",");
                                try {
                                    $scope.urlParameterSearchParcelID = appConfig["urlParameterSearches"]["parcelID"];
                                    $scope.urlParameterSearchOwnerName = appConfig["urlParameterSearches"]["ownerName"];
                                    $scope.urlParameterSearchAddress = appConfig["urlParameterSearches"]["address"];
                                }
                                catch {
                                    $scope.urlParameterSearchParcelID = null;
                                    $scope.urlParameterSearchOwnerName = null;
                                    $scope.urlParameterSearchAddress = null;
                                }
                                $scope.fromNearby = false;
                                $scope.initParcelFields = appConfig["initParcelFields"].split(",");
                                $scope.queryParcelFields = appConfig["queryParcelFields"].split(",");

                                $scope.noIdentifyLayers = appConfig["noIdentifyLayers"].split(",");
                                $scope.noIdentifyFields = appConfig["noIdentifyFields"].split(",");

                                $scope.currencyFields = appConfig["currencyFields"].split(",");
                                $scope.dateFields = appConfig["dateFields"].split(",");
                                try {
                                    $scope.customDateFields = appConfig["customDateFields"].split(",");
                                } catch (err) {
                                    $scope.customDateFields = [];
                                }
                                $scope.numberFields = appConfig["numberFields"].split(",");
                                $scope.firstCapFields = appConfig["firstCapFields"].split(",");
                                $scope.allCapFields = appConfig["allCapFields"].split(",");
                                $scope.noNaFields = appConfig["noNaFields"].split(",");
                                try {
                                    $scope.nullAsNullFields = appConfig["nullAsNullFields"].split(",");
                                }
                                catch {
                                    $scope.nullAsNullFields = [];
                                }

                                $scope.replaceField = appConfig["replaceField"];
                                try {
                                    var temp = $scope.replaceField.length;
                                } catch (err) {
                                    $scope.replaceField = [];
                                }

                                $scope.checkboxList = [];
                                $scope.onList = [];
                                districtOptions = appConfig["districtOptions"].split(",");
                                //$scope.csvHeaderField = JSON.parse("[" + appConfig["csvHeaderField"] + "]");
                                $scope.csvSResultField = appConfig["csvSResultField"];
                                $scope.csvHeaderField = appConfig["csvHeaderField"];
                                try {
                                    var temp = $scope.csvSResultField.length;
                                } catch (err) {
                                    $scope.csvSResultField = $scope.csvHeaderField;
                                }
                                $scope.csvHeaderPtField = appConfig["csvHeaderPtField"];

                                $scope.selectedDistrict = undefined;
                                $scope.searchDistricts = districtOptions;
                                /*$scope.districtComparator = function (searchDistricts, viewValue) {
                                    return viewValue === secretEmptyKey || (''+searchDistricts).toLowerCase().indexOf((''+viewValue).toLowerCase()) > -1;
                                };*/


                                //Start Fastclick, define prototypes and objects we'll need later...
                                //new FastClick(document.body);

                                $scope.createList = function () { layersUI.createList($scope, $location); }
                                //==code for secureSite== 
                                layersUI.createList($rootScope, $scope, $location);
                                //==end==
                                String.prototype.capitalize = function (lower) {
                                    return (lower ? this.toLowerCase() : this).replace(/(?:^|\s)\S/g, function (a) {
                                        return a.toUpperCase();
                                    });
                                };

                                Array.prototype.contains = function (element) {
                                    return this.indexOf(element) > -1;
                                };

                                $scope.rgbToHex = function (r, g, b) {
                                    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
                                };

                                $scope.zoomToggles = [];
                                $scope.lastDragged = null;
                                $scope.legend = {
                                    buildings: [],
                                    zones: []
                                };

                                //===gray image (background) effect                    
                                var msie = wlFactory.detectIE();

                                if (msie != false) //if IE
                                {
                                    $('.grayscale_logo').gray();
                                    $('#backgroundContainer').children('img').addClass('logobg'); //for IE9
                                    $('.grayscale_list').gray();
                                    $('.grayscale_map').gray();
                                    $('.layerVis').gray();
                                }
                                //===end of gray image (background) effect


                                $scope.disabled = function (date, mode) {
                                    return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
                                };

                                $scope.datePicker1 = {
                                    opened: false
                                };
                                $scope.datePicker2 = {
                                    opened: false
                                };
                                $scope.dateOptions = {
                                    formatYear: 'yy',
                                    startingDay: 1
                                };
                                $scope.initDate = new Date('2016-15-20');
                                $scope.formats = ['MM/dd/yyyy'];
                                $scope.format = $scope.formats[0];

                                $scope.priceMin = $scope.searchPriceMin; //0
                                $scope.priceMax = $scope.searchPriceMax; //10000000

                                $("#priceSlider").noUiSlider({
                                    start: [$scope.priceMin, $scope.priceMax],
                                    connect: true,
                                    range: {
                                        'min': $scope.priceMin,
                                        '40%': $scope.priceMax / 100,
                                        '80%': $scope.priceMax / 10,
                                        'max': $scope.priceMax
                                    },
                                    step: 10000
                                });

                                $("#priceSlider").Link('lower').to($('#priceSlider-value-min'), null, wNumb({
                                    decimals: 0,
                                    thousand: ',',
                                    prefix: '$',
                                }));

                                $("#priceSlider").Link('upper').to($('#priceSlider-value-max'), null, wNumb({
                                    decimals: 0,
                                    thousand: ',',
                                    prefix: '$',
                                }));

                                $scope.immediateAdjoiners = true;
                                $scope.showPanel2 = false;
                                $scope.showAdjoiner = false;
                                $scope.adjoinerBufferDistance = 0;

                                $scope.Units = ['Feet', 'Meters', 'Miles'];
                                $scope.SelectedUnit = $scope.Units[0];

                                $scope.LineUnits = ['Feet', 'Meters', 'Miles'];
                                $scope.SelectedLineUnit = $scope.LineUnits[0];

                                $scope.PolygonUnits = ['Acres', 'Square Feet'];
                                $scope.SelectedPolygonUnit = $scope.PolygonUnits[0];

                                $scope.stackedFeature = false;
                                $scope.stackedFeatureStatus = false;
                                $scope.searchTarget = '';

                                //$scope.DTool = [{value:'POLYLINE', name:'Line'},{value:'FREEHAND_POLYLINE', name:'Line-Freehand'},{value:'POLYGON', name:'Polygon'},{value:'FREEHAND_POLYGON', name:'Polygon-Freehand'}];
                                //$scope.DTool = [{value:'POLYLINE', name:'Line'},{value:'POLYGON', name:'Polygon'}];
                                //$scope.SelectedDTool = $scope.DTool[0];

                                $scope.getBase64Image = function (url, convImg) {
                                    var img = new Image();
                                    img.setAttribute('crossOrigin', 'anonymous');
                                    img.onload = function () {
                                        var canvas = document.createElement("canvas");
                                        canvas.width = this.width * 1;
                                        canvas.height = this.height * 1;

                                        var ctx = canvas.getContext("2d");
                                        ctx.drawImage(this, 0, 0);

                                        var dataURL = canvas.toDataURL("image/png");
                                        if (convImg == "header") {
                                            $scope.headerData = dataURL;
                                        } else if (convImg == "marker") {
                                            $scope.PictureMarkerSymbolData = dataURL.toString().replace('data:image/png;base64,', '');

                                        }

                                    };
                                    img.src = url;
                                }
                                var markerImage = $scope.bookmarkMarkerImage; //bookmark marker
                                $scope.PictureMarkerSymbolData = $scope.getBase64Image(markerImage, "marker");


                                var headerImage = $scope.pdfHeaderImage; //pdf report header
                                $scope.headerData = $scope.getBase64Image(headerImage, "header");

                                $scope.selectedParcel = {};
                                $scope.queryResults = [];
                                $scope.emptySearch = false;
                                $scope.emptyAdjoiner = false;
                                $scope.selectDate = function (dt) {
                                    //console.log(dt);
                                }
                                $scope.getSDate = function (dt) {
                                    //console.log($("#dateFrom").value);
                                }
                                $("#cal1").on('changeDate', function (ev) {
                                    window.location.href = "?day=" + ev.format();
                                });
                                $("#dateFrom").on('change', function (ev) {
                                    window.location.href = "?day=" + ev.format();
                                });
                                $('#dateFrom').on('input', function () {
                                    $(this).val();
                                });

                                setTimeout(function () { //begin setTimeout***
                                    panelControl.setIscroll($scope);
                                    if ($scope.immediateAdjoiners == true) {
                                        $("#customBuffer").addClass("fadeOut");
                                    }

                                    var selAdvField = "advTaxMap";

                                    $scope.optionComparator = function (searchOptions, viewValue) {
                                        return viewValue === secretEmptyKey || ('' + searchOptions).toLowerCase().indexOf(('' + viewValue).toLowerCase()) > -1;
                                    };
                                    $scope.option2Comparator = function (searchDistricts, viewValue) {
                                        return viewValue === secretEmptyKey || ('' + searchDistricts).toLowerCase().indexOf(('' + viewValue).toLowerCase()) > -1;
                                    };
                                    $scope.onOptionSelect = function (e) {
                                        var targetId = event.target.parentElement.parentElement.previousSibling.id; //alert(targetId);            
                                        setTimeout(function () {
                                            $("#" + targetId).nextAll('ul').first().css('display', 'none');
                                            var el = document.getElementById(targetId);
                                            //ev = document.createEvent('Event');
                                            //ev.initEvent('change', true, false);
                                            //el.dispatchEvent(ev);
                                            el.blur();
                                        }, 50);
                                    }
                                    $scope.onFocus = function (e) {
                                        // Many sites use this function for the advanced search but was not specific to any one site configuration
                                        // Moved from localCustom into app.js
                                        // localCustom.onFocus(e);
                                        $(e.target).parent().find("ul").css('display', 'block');

                                        //$timeout(function () {
                                        setTimeout(function () {
                                            var tempVal = $(e.target).val();
                                            $(e.target).val(secretEmptyKey).trigger("input");
                                            $(e.target).val(tempVal);
                                            $(e.target).trigger('input');
                                            $(e.target).trigger('change');
                                        }, 0);
                                    };

                                    $scope.popup = new esriPopup({
                                        keepHighlightOnHide: ($scope.keepHighlightOnHide === "true"),
                                        fillSymbol: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
                                            new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                                                new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25]))
                                    }, $scope.domConstruct.create("div"));

                                    initx = appConfig["initx"] * 1;
                                    inity = appConfig["inity"] * 1;
                                    initzoom = appConfig["initzoom"] * 1;

                                    if (appConfig["minZoom"] == null) {
                                        minZoom = 8;
                                    }
                                    else {
                                        minZoom = appConfig["minZoom"] * 1;
                                    }

                                    if (appConfig["maxZoom"] == null) {
                                        maxZoom = 19;
                                    }
                                    else {
                                        maxZoom = appConfig["maxZoom"] * 1;
                                    }


                                    if (window.innerWidth < 601) {
                                        initzoom -= 1;
                                    }
                                    if ($scope.sliderStyle == 'large') {
                                        $scope.labels = ['292,828,764', '73,957,191', '18,459,298', '4,622,324', '1,155,581', '288,895', '72,224', '18,056', '4,514', '1,128', '282', '71'];
                                    }

                                    $scope.map = new Map("map", {
                                        center: [initx, inity],
                                        zoom: initzoom,
                                        minZoom: minZoom,
                                        maxZoom: maxZoom,
                                        basemap: "streets",
                                        showLabels: true,
                                        sliderStyle: $scope.sliderStyle,
                                        infoWindow: $scope.popup,
                                        smartNavigation: false
                                    });
                                    if ($scope.draggableParcelIdentify == 'true') {
                                        //===for dragging popup
                                        var handle = dojoQuery(".title", $scope.map.infoWindow.domNode)[0]
                                        $scope.dnd = new dojoMoveable($scope.map.infoWindow.domNode, {
                                            handle: handle
                                        });
                                        // when the infoWindow is moved, hide the arrow:
                                        on($scope.dnd, 'FirstMove', function () {
                                            // hide pointer and outerpointer (used depending on where the pointer is shown)
                                            var arrowNode = dojoQuery(".outerPointer", $scope.map.infoWindow.domNode)[0];
                                            domClass.add(arrowNode, "hidden");

                                            var arrowNode = dojoQuery(".pointer", $scope.map.infoWindow.domNode)[0];
                                            domClass.add(arrowNode, "hidden");
                                        }.bind(this));
                                        //======
                                    }

                                    $scope.map.infoWindow.hide();
                                    $scope.navToolbar = new Navigation($scope.map);
                                    $scope.toolbar = new $scope.Draw($scope.map, {
                                        showTooltips: true
                                    });
                                    $scope.esriConfig.defaults.geometryService = new $scope.GeometryService($scope.geometryServiceUrl);
                                    $scope.esriConfig.defaults.io.alwaysUseProxy = false;
                                    $scope.bufferSymbol = new $scope.SimpleFillSymbol(
                                        $scope.SimpleFillSymbol.STYLE_SOLID,
                                        new $scope.SimpleLineSymbol(
                                            $scope.SimpleLineSymbol.STYLE_SOLID,
                                            new $scope.Color([1, 105, 202, 0.3]),
                                            3
                                        ),
                                        new $scope.Color([255, 255, 255, 0.3])
                                    );

                                    $scope.highlightSymbol = new $scope.SimpleFillSymbol(
                                        $scope.SimpleFillSymbol.STYLE_SOLID,
                                        new $scope.SimpleLineSymbol(
                                            $scope.SimpleLineSymbol.STYLE_SOLID,
                                            new $scope.Color([255, 0, 0]),
                                            2
                                        ),
                                        new $scope.Color([0, 0, 0, 0.25])
                                    );
                                    $scope.selParcelSymbol = new $scope.SimpleFillSymbol(
                                        $scope.SimpleFillSymbol.STYLE_NULL,
                                        new $scope.SimpleLineSymbol(
                                            $scope.SimpleLineSymbol.STYLE_SOLID,
                                            new $scope.Color([$scope.selParcelSymbolLine[0], $scope.selParcelSymbolLine[1], $scope.selParcelSymbolLine[2]]),
                                            $scope.selParcelSymbolLine[3]
                                        ),
                                        new $scope.Color([$scope.selParcelSymbolFill[0], $scope.selParcelSymbolFill[1], $scope.selParcelSymbolFill[2], $scope.selParcelSymbolFill[3]])
                                    );
                                    $scope.mSelParcelSymbol = new $scope.SimpleFillSymbol(
                                        $scope.SimpleFillSymbol.STYLE_SOLID,
                                        new $scope.SimpleLineSymbol(
                                            $scope.SimpleLineSymbol.STYLE_SOLID,
                                            new $scope.Color([1, 255, 255, 1]),
                                            2
                                        ),
                                        new $scope.Color([255, 255, 0, 0.2])
                                    );
                                    $scope.mSelPointSymbol = new $scope.SimpleMarkerSymbol(
                                        new $scope.SimpleMarkerSymbol(
                                            $scope.SimpleMarkerSymbol.STYLE_CIRCLE,
                                            $scope.mSelPointSymbolSize,
                                            new $scope.SimpleLineSymbol(
                                                $scope.SimpleLineSymbol.STYLE_SOLID,
                                                new $scope.Color($scope.mSelPointSymbolLine),
                                                2
                                            ),
                                            new $scope.Color($scope.mSelPointSymbolColor)
                                        ));
                                    $scope.drawSymbol = new $scope.SimpleFillSymbol(
                                        $scope.SimpleFillSymbol.STYLE_SOLID,
                                        new $scope.SimpleLineSymbol(
                                            $scope.SimpleLineSymbol.STYLE_SOLID,
                                            new $scope.Color([1, 105, 202]),
                                            3
                                        ),
                                        new $scope.Color([255, 255, 255, 0.5])
                                    );

                                    $scope.navToolbar.on("extent-history-change", extentHistoryChangeHandler);
                                    $scope.toolbar.setFillSymbol($scope.highlightSymbol);

                                    function extentHistoryChangeHandler() {
                                        mapTools.extentHistoryChangeHandler($scope);
                                    }
                                    //-----previous btnnavToolbar
                                    $("#previousBtn").click(function (e) {
                                        e.preventDefault();
                                        if (!$scope.navToolbar.isFirstExtent()) {
                                            $scope.navToolbar.zoomToPrevExtent();
                                        }
                                    });
                                    //-----next btn
                                    $("#nextBtn").click(function (e) {
                                        e.preventDefault();
                                        if (!$scope.navToolbar.isLastExtent()) {
                                            $scope.navToolbar.zoomToNextExtent();
                                        }
                                    });
                                    $scope.parcelSymbol = new SimpleFillSymbol(
                                        SimpleFillSymbol.STYLE_SOLID,
                                        new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([200, 200, 200]), 2),
                                        new Color([125, 125, 125, 0])
                                    );
                                    $scope.parcelSymbolNull = new SimpleFillSymbol(
                                        SimpleFillSymbol.STYLE_NULL,
                                        new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([200, 200, 200]), 2),
                                        new Color([125, 125, 125, 1])
                                    );
                                    $scope.layersArray = {};

                                    esri.config.defaults.io.corsEnabledServers.push($scope.corsEnabledServersUrl);
                                    esri.config.defaults.io.timeout = 180000;

                                    var imageParameters = new ImageParameters();
                                    if (initLayerIds[0].length > 0) {
                                        imageParameters.layerIds = initLayerIds; //initial layer ids defined in config.json
                                    } else {
                                        imageParameters.layerIds = $scope.initLayerIdsArray; // initial layer ids detected from layersUI.createList()
                                    }
                                    imageParameters.layerOption = ImageParameters.LAYER_OPTION_SHOW;
                                    //can also be: LAYER_OPTION_EXCLUDE, LAYER_OPTION_HIDE, LAYER_OPTION_INCLUDE
                                    if ($scope.isFeatureService) {
                                        for (var i = $scope.mapLayers.length - 1; i >= 0; i--) {
                                            var opts = {
                                                mode: $scope.FeatureLayer.MODE_AUTO,
                                                id: $scope.mapLayers[i].name,
                                                outFields: ["*"],
                                                visible: $scope.mapLayers[i].defaultVisibility,
                                                showLabels: true
                                            }
                                            if ($scope.mapLayers[i].name != $scope.parcelLayerName) {
                                                var fl = new $scope.FeatureLayer($scope.featureServUrl + $scope.mapLayers[i].id, opts)
                                                $scope.map.addLayer(fl);
                                            }
                                        }
                                    }
                                    else {
                                        opts = {};
                                        opts.imageParameters = imageParameters;
                                        opts.id = "map_layer1";
                                        $scope.dmsLayer = new ArcGISDynamicMapServiceLayer(WMSLayerUrl, opts);
                                        $scope.map.addLayer($scope.dmsLayer);
                                        $scope.dmsLayer.setDPI(96);
                                    }

                                    //===parcel (feature) layer =====
                                    var opts = {
                                        mode: $scope.FeatureLayer.MODE_AUTO,
                                        opacity: 1,
                                        outFields: $scope.initParcelFields,
                                        visible: true,
                                        showLabels: true,
                                        id: $scope.parcelLayerName
                                    }
                                    $scope.parcelLayer = new $scope.FeatureLayer($scope.queryTaskUrl, opts);
                                    $scope.openAssessmentDelay = 0; //to prevent multiple call
                                    $("#assessmentLink").click(function (e) {
                                        if ($scope.openAssessmentDelay == 0) {
                                            var conf = window.confirm("This link will open up a separate tab.");
                                            if (conf == true) {
                                                window.open($scope.selectedParcel.AssessLink);
                                            }
                                            $scope.openAssessmentDelay = 1;
                                        }
                                        setTimeout(function () {
                                            $scope.openAssessmentDelay = 0;
                                        }, 1000);
                                    });
                                    // Disabled this function during migration to AGOL. Better to set all labels at the feature service if possible
                                    //==========add labelLayers==========
                                    // var TColor = new $scope.Color("#484848");
                                    // var layerLabel = new TextSymbol().setColor(TColor);
                                    // layerLabel.font.setSize("10px");
                                    // layerLabel.font.setFamily("arial");
                                    // layerLabel.font.setWeight("bold");
                                    // var layerLabelRenderer = new UniqueValueRenderer(layerLabel);
                                    // var layerLabel1 = new TextSymbol().setColor(TColor);
                                    // layerLabel1.font.setSize("10px");
                                    // layerLabel1.font.setFamily("arial");
                                    // //layerLabel1.font.setStyle("italic");
                                    // layerLabel1.font.setWeight("normal");
                                    // layerLabel1.setOffset(0, -9);
                                    // var layerLabelRenderer1 = new UniqueValueRenderer(layerLabel1);
                                    // //console.log(labelArray);
                                    // if (labelArray[0][0].length > 0) {
                                    //     lVisible = true;
                                    //     for (var l = 0; l < labelArray.length; l++) {
                                    //         var flabelLayer = new FeatureLabelLayer({
                                    //             id: labelArray[l][0] + "labels" + l,
                                    //             mode: "static",
                                    //             opacity: 0.7,
                                    //             visible: true
                                    //         });
                                    //         flabelLayer.minScale = 5000;
                                    //         flabelLayer.maxScale = 50;
                                    //         // using the field name for labels
                                    //         if (l == 0) {
                                    //             flabelLayer.addFeatureLayer($scope.parcelLayer, layerLabelRenderer, "{" + labelArray[l][1] + "}");
                                    //         } else {
                                    //             flabelLayer.addFeatureLayer($scope.parcelLayer, layerLabelRenderer1, "{" + labelArray[l][1] + "}");
                                    //         }
                                    //         $scope.map.addLayer(flabelLayer);
                                    //     }
                                    // }
                                    //========== end of adding labelLayers==========        

                                    //dojo.keys.copyKey maps to CTRL on windows and Cmd on Mac., but has wrong code for Chrome on Mac
                                    var snapManager = $scope.map.enableSnapping({
                                        snapKey: has("mac") ? keys.META : keys.CTRL
                                    });
                                    var layerInfos = [{
                                        layer: $scope.parcelLayer
                                    }];
                                    snapManager.setLayerInfos(layerInfos);

                                    $scope.bufferLayer = new GraphicsLayer({
                                        id: 'buffer'
                                    });
                                    $scope.bmLayer = new GraphicsLayer({
                                        id: 'bmPt'
                                    });
                                    $scope.selectedLayer = new GraphicsLayer({
                                        id: 'select'
                                    });
                                    $scope.multiSelectedLayer = new GraphicsLayer({
                                        id: 'multiSelect'
                                    });
                                    $scope.drawLayer = new GraphicsLayer({
                                        id: 'draw'
                                    });
                                    $scope.labelLayer = new GraphicsLayer({
                                        id: 'label'
                                    });
                                    $scope.drawLayerForSelect = new GraphicsLayer({
                                        id: 'drawForSelect'
                                    });

                                    $scope.sms = new $scope.SimpleMarkerSymbol({
                                        "color": [255, 255, 255, 100],
                                        "size": 8,
                                        //"angle": -30,
                                        "xoffset": 0,
                                        "yoffset": 0,
                                        "type": "esriSMS",
                                        "style": "esriSMSCircle",
                                        "outline": {
                                            "color": [0, 0, 255, 200],
                                            "width": 2,
                                            "type": "esriSLS",
                                            "style": "esriSLSSolid"
                                        }
                                    });
                                    dialog = new TooltipDialog({
                                        //id: "tooltipDialog",
                                        style: "position: absolute; width: 250px; font: normal normal normal 10pt Helvetica; z-index:100"
                                    });
                                    dialog.startup();

                                    $scope.sps = new $scope.PictureMarkerSymbol({
                                        "url": "img/marker5.png",
                                        "height": 30,
                                        "width": 15,
                                        "xoffset": 0,
                                        "yoffset": 12,
                                        "type": "esriPMS",
                                        "angle": 0,
                                        "imageData": $scope.PictureMarkerSymbolData
                                    });
                                    $scope.myLocSymbolData = wlFactory.getMyLocMarkerData();
                                    $scope.mlsd = new $scope.PictureMarkerSymbol({
                                        "url": "img/location.png",
                                        "height": 16,
                                        "width": 16,
                                        "xoffset": 0,
                                        "yoffset": 0,
                                        "type": "esriPMS",
                                        "angle": 0,
                                        "imageData": $scope.myLocSymbolData
                                    });
                                    $scope.bufferLayer.setRenderer(new SimpleRenderer($scope.bufferSymbol));
                                    $scope.map.addLayer($scope.bufferLayer);

                                    $scope.multiSelectedLayer.setRenderer(new SimpleRenderer($scope.mSelParcelSymbol));
                                    $scope.map.addLayer($scope.multiSelectedLayer);

                                    //$scope.selectedLayer.setRenderer(new SimpleRenderer($scope.highlightSymbol));                        
                                    $scope.map.addLayer($scope.parcelLayer);
                                    $scope.parcelLayer.setRenderer(new SimpleRenderer($scope.parcelSymbol));

                                    $scope.selectedLayer.setRenderer(new SimpleRenderer($scope.selParcelSymbol));
                                    $scope.map.addLayer($scope.selectedLayer);

                                    $scope.bmLayer.setRenderer(new SimpleRenderer($scope.sps));
                                    $scope.map.addLayer($scope.bmLayer);

                                    $scope.drawLayer.setRenderer(new SimpleRenderer($scope.drawSymbol));
                                    $scope.map.addLayer($scope.drawLayer);
                                    $scope.map.addLayer($scope.labelLayer);

                                    $scope.drawLayerForSelect.setRenderer(new SimpleRenderer($scope.drawSymbol));
                                    $scope.map.addLayer($scope.drawLayerForSelect);



                                    Array.prototype.naturalSort = function () {
                                        var a, b, a1, b1, rx = /(\d+)|(\D+)/g,
                                            rd = /\d+/;
                                        return this.sort(function (as, bs) { //as and bs: addresses
                                            a = String(as).toLowerCase().match(rx); //a and b are address number & "," & street name
                                            b = String(bs).toLowerCase().match(rx);
                                            var t = 0;
                                            while (a.length && b.length) {
                                                a1 = a.shift(); //a1 and b1 are address number 
                                                b1 = b.shift();
                                                if (rd.test(a1) || rd.test(b1)) {
                                                    if (!rd.test(a1)) return 1;
                                                    if (!rd.test(b1)) return -1;
                                                    if (a1 != b1) return a1 - b1;
                                                } else if (a1 != b1) return a1 > b1 ? 1 : -1;
                                                t++; //console.log(t);
                                            }

                                            return a.length - b.length;
                                        });
                                    }
                                    Array.prototype.naturalArraySort = function () {
                                        var a, b, a1, b1, rx = /(\d+)|(\D+)/g,
                                            rd = /\d+/;
                                        return this.sort(function (as, bs) {
                                            a = String(as).toLowerCase().match(rx);
                                            b = String(bs).toLowerCase().match(rx);
                                            while (a.length && b.length) {
                                                a1 = a.shift();
                                                b1 = b.shift();
                                                if (rd.test(a1) || rd.test(b1)) {
                                                    if (!rd.test(a1)) return 1;
                                                    if (!rd.test(b1)) return -1;
                                                    if (a1 != b1) return a1 - b1;
                                                } else if (a1 != b1) return a1 > b1 ? 1 : -1;
                                            }
                                            return a.length - b.length;
                                        });
                                    }
                                    $scope.queryObjectId = function (oid, OBJECTID, selBtn, layer) {
                                        //$("#detailPreloaderContainer").addClass("active");$scope.$apply();
                                        $scope.selDetailPanel = selBtn;
                                        $scope.selObject = layer;
                                        try {
                                            var temp = $scope.selObject.length;
                                        } catch (err) {
                                            $scope.selObject = 'pl';
                                        }

                                        if (layer == 'pt') {
                                            $scope.numOfSubTable = 1; //to add building section table in the pdf report
                                            var queryGeom = new $scope.QueryTask($scope.searchPtUrl);
                                            var queryGeometry = new $scope.Query();
                                            queryGeometry.returnGeometry = true;
                                            queryGeometry.outFields = ["*"];
                                            queryGeometry.where = $scope.addrPtUid + "='" + oid + "'";
                                            queryGeom.execute(queryGeometry, $scope.queryObjectIdResults);
                                            if ($scope.customRelatedFld == 'true') {
                                                setTimeout($scope.findRelatedRecords(oid), 100);
                                            }
                                        } else { //if it is for parcel polygon layer
                                            var queryGeom = new QueryTask(queryGeomUrl);
                                            var queryGeometry = new Query();
                                            queryGeometry.returnGeometry = true;
                                            queryGeometry.outFields = $scope.queryParcelFields
                                            if (typeof $scope.selectedParcel[$scope.parcelUid] === "string") {
                                                var where = $scope.parcelUid + "='" + oid + "'"
                                            }
                                            else {
                                                var where = $scope.parcelUid + "=" + oid
                                            }
                                            queryGeometry.where = where;
                                            queryGeom.execute(queryGeometry, $scope.queryObjectIdResults);
                                            if ($scope.customRelatedFld == 'true') {
                                                setTimeout($scope.findRelatedRecords(OBJECTID), 100);
                                            }
                                        }
                                    }
                                    //$scope.customQueryObjectIdResults     = function(results) { $scope.localCustom.queryObjectIdResults(results, $scope);}
                                    $scope.queryObjectIdResults = function (results) {
                                        //$("#detailPreloaderContainer").addClass("active");
                                        results = results.features;
                                        $scope.combine1 = '';
                                        $scope.combine2 = '';
                                        var result = results[0];
                                        var totVal = 0;
                                        if ($scope.sumQueryResultFld.length > 1) {
                                            for (var j = 0; j < $scope.sumQueryResultFld.length; j++) {
                                                totVal += parseInt(result.attributes[$scope.sumQueryResultFld[j]]);
                                            }
                                        }

                                        for (var key in result.attributes) {
                                            thisKey = result.attributes[key.toString()]; //alert(key); alert(thisKey); //key=fieldname, thisKey=value

                                            result.attributes[key.toString()] = $scope.formatParcelData(key, thisKey, result.attributes[key.toString()]);
                                            result.attributes.geometry = result.geometry;
                                        }
                                        $scope.selectedParcel = result.attributes;

                                        if ($scope.sumQueryResultFld.length > 1) {
                                            $scope.selectedParcel['customTotVal'] = $scope.formatParcelData('customTotVal', totVal, $scope.selectedParcel['customTotVal']);
                                        }
                                        //call related table query
                                        //$scope.findRelatedRecords($scope.selectedParcel['OBJECTID']);
                                        $scope.immediateAdjoiners = true;

                                        if ($scope.selDetailPanel != 'p1-1' && !($scope.selDetailPanel == 'p1' && window.innerWidth < 651)) { //not from selected parcel lists and resultlists with <651
                                            $scope.getAdjoiners();
                                        }

                                        //add something for final wrap up

                                        //$scope.$apply();
                                        setTimeout($scope.myScroll2.refresh(), 500);
                                        setTimeout($scope.myScroll3.refresh(), 600);
                                        if (window.innerWidth < 651) {
                                            $scope.map.infoWindow.hide();

                                            if ($scope.showPanel2 == true) {
                                                $("#panel1").removeClass("active");
                                                $("#panel1").addClass("inactive"); //to hide iscroll of panel1
                                                $("#panel2").addClass("active");
                                                //setTimeout($scope.refreshIscroll(), 300);
                                            } else {
                                                $scope.hidePanel2();
                                                //setTimeout($scope.refreshIscroll(), 400);
                                                //$("#panel1").animate({scrollTop: $("#panel1Buttons").offset().top-1}, 100);
                                                //$scope.refreshIscroll();
                                                //setTimeout(function(){$scope.refreshIscroll();$("#panel1").scrollTop(0);$("#panel2").scrollTop(0);}, 400);
                                            }
                                        } else if (window.innerWidth > 650) {
                                            if ($scope.selDetailPanel != 'map' && $scope.selDetailPanel != 'm' && $scope.selDetailPanel != 'p1') {
                                                $scope.switchParcelDetails($scope.selDetailPanel);
                                                $("#detailPanels").addClass("active");
                                                $("#panel1").addClass("active");
                                                $("#panel1").removeClass("inactive");
                                                if ($scope.selDetailPanel == 'adjoiner') {
                                                    $scope.showAdjoiner = true;
                                                }
                                                $scope.showDetail();

                                            }
                                        }
                                        setTimeout($scope.myScroll2.refresh(), 300);
                                        setTimeout($scope.myScroll3.refresh(), 300);
                                        $scope.$apply();
                                    }

                                    //assigning clickable layer. mouse-over effect is in css file (#Parcels_layer)    

                                    $scope.identifyTask = new $scope.IdentifyTask($scope.featureServUrl);
                                    $scope.identifyParams = new $scope.IdentifyParameters();
                                    $scope.identifyParams.tolerance = 2;
                                    $scope.identifyParams.returnGeometry = true;
                                    $scope.identifyParams.layerOption = $scope.IdentifyParameters.LAYER_OPTION_ALL; //_ALL, _VISIBLE, _TOP
                                    $scope.identifyParams.width = $scope.map.width;
                                    $scope.identifyParams.height = $scope.map.height;

                                    $scope.parcelLayer.on("click", function (evt) {
                                        layerEvent.parcelClick($scope, evt);
                                    }); //end of parcelLayer.onclick  

                                    $scope.parcelLayer.on("graphic-draw", function (evt) {
                                        /*$("#"+$scope.parcelLayerName+"_layer path").hover(
                                            function(){ 
                                            $(this).css("fill", "rgba(1,105,202,1)");
                                            $(this).css("fill-opacity", "0.1");                            
                                        }, 
                                        function(){
                                            $(this).css("fill-opacity", "0");
                                            }
                                        ); 
                                        $("#"+$scope.parcelLayerName+"_layer path").css('stroke-width','3');
                                        $("#"+$scope.parcelLayerName+"_layer path").css('cursor','pointer');*/
                                        //$("#"+$scope.parcelLayerName+"_layer path").css('hover','3');

                                        if ($("#identifyButton").hasClass("selected")) {
                                            $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/cursor7.cur),default');
                                            $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/cursor7.png) 3 1,auto');
                                        } else if ($("#GSButton").hasClass("selected")) {
                                            $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/gsCursor25.cur),default');
                                            $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/gsCursor25.png) 12 25,auto');
                                        }
                                    });

                                    $('#viewParcelDetails').on("click touchstart", function () {
                                        $scope.switchParcelDetails('detail')
                                    });
                                    $('#viewAdjoinerList').on("click touchstart", function () {
                                        $scope.switchParcelDetails('adjoiner')
                                    });

                                    $scope.immediateAdjToggleDelay = 0;	//to prevent multiple call						
                                    $("#bufferCboxDiv").on("click touchstart", function (evt) {
                                        if ($scope.immediateAdjToggleDelay == 0) {
                                            $scope.immediateAdjToggleDelay = 1;
                                            switch ($scope.immediateAdjoiners) {
                                                case true:
                                                    $("#customBuffer").removeClass("fadeOut");
                                                    $scope.immediateAdjoiners = false;
                                                    $("#immediateAdjoinersToggle").prop('checked', false);
                                                    $("#adjoinerDistance").focus();
                                                    break;
                                                default:
                                                    $("#immediateAdjoinersToggle").prop('checked', true);
                                                    $("#customBuffer").addClass("fadeOut");
                                                    $("#adjoinerDistance").blur();
                                                    $scope.immediateAdjoiners = true;
                                                    $scope.getAdjoiners();
                                                    break;
                                            }
                                            if ($("#adjoinerDistance").val().length < 1) {
                                                $("#refreshSearch").addClass("fadeOut");
                                            } else {
                                                $("#refreshSearch").removeClass("fadeOut");
                                            }
                                        }
                                        setTimeout(function () { $scope.immediateAdjToggleDelay = 0; }, 1000);
                                    });
                                    //===================================
                                    $scope.drawLayer.on("click", function (drawing) {
                                        layerEvent.drawLayerOnClick($scope, drawing);
                                    });
                                    $scope.drawLayer.on("mouse-over", function (evt) {
                                        layerEvent.drawLayerOnMouseOver(evt);
                                    });
                                    $scope.drawLayer.on("mouse-out", function (evt) {
                                        layerEvent.drawLayerOnMouseOut(evt)
                                    });
                                    $scope.drawLayerForSelect.on("graphic-add", function (event) {
                                        layerEvent.drawLayerOnGraphicAdd($scope, event)
                                    });
                                    $scope.drawLayer.on("graphic-add", function (event) {
                                        layerEvent.drawLayerOnGraphicAdd($scope, event)
                                    });
                                    $scope.labelLayer.on("click", function (label) {
                                        layerEvent.labelLayerOnClick($scope, label);
                                    });
                                    $scope.labelLayer.on("graphic-add", function (event) {
                                        layerEvent.labelLayerOnGraphicAdd($scope, event);
                                    });
                                    $scope.map.on("load", function (event) {
                                        mapFunction.mapOnLoad($scope, $location, event);
                                    });
                                    $scope.showCursorCoordinates = function (evt) {
                                        var mp = $scope.webMercatorUtils.webMercatorToGeographic(evt.mapPoint);
                                        if ($scope.multipleCoordinateDisplay == 'true') {
                                            if (dom.byId("cursorLocOption").innerHTML == 'X,Y') { //for Lon, Lat
                                                dom.byId("cursorLoc").innerHTML = mp.x.toFixed(6) + ", " + mp.y.toFixed(6);
                                            } else { //for degrees                            
                                                var x = $scope.ConvertDDToDMS(mp.x, true);
                                                var y = $scope.ConvertDDToDMS(mp.y, false);
                                                dom.byId("cursorLoc").innerHTML = x.deg + "&ordm; " + x.min + "&#34; " + x.sec + "&#39; " + x.dir + ", " + y.deg + "&ordm; " + y.min + "&#34; " + y.sec + "&#39; " + y.dir;
                                            }
                                        } else {
                                            dom.byId("cursorLoc").innerHTML = mp.x.toFixed(6) + ", " + mp.y.toFixed(6);
                                        }
                                    }
                                    $scope.showMapScale = function (evt) {
                                        if ($scope.sliderStyle == 'large') {
                                            var mapScale = $scope.map.getScale();
                                            var mapLevel = $scope.map.getLevel();

                                            dom.byId("mapScale").innerHTML = "1:" + mapScale.toFixed(0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                                            $("#userMapScale").val(mapScale.toFixed(0));
                                            var top = 215;
                                            var multi = mapLevel - 7;
                                            $("#mapScale").css('top', (top - multi * 14));
                                        }
                                    }
                                    $scope.map.on("mouse-move", $scope.showCursorCoordinates);
                                    //$scope.map.on("load", setTimeout(function(event){mapFunction.mapOnLoad($scope, $location, event);}, 400));
                                    $scope.showCoordinates = function (evt) {
                                        setTimeout(function () {
                                            var geo = $scope.map.geographicExtent;
                                            var ctrX = (geo.xmin + geo.xmax) / 2;
                                            var ctrY = (geo.ymin + geo.ymax) / 2;
                                            $location.search('location', ctrX.toFixed(6) + '_' + ctrY.toFixed(6));
                                            $scope.$apply();
                                        }, 100);
                                    }

                                    $scope.pRatio = 1;
                                    $('#userMapScale').bind('input', function () {
                                        if ($("#printPreviewContainer").hasClass("active")) {
                                            $scope.pRatio = $(this).val() / $scope.currentMapScale;
                                            mapTools.updatePrintPreviewBox($scope);
                                        }

                                    });
                                    $("#printSize").change(function () {
                                        $scope.pRatio = $('#userMapScale').val() / $scope.currentMapScale;
                                        mapTools.updatePrintPreviewBox($scope);
                                    });

                                    $scope.updateExtent = function (evt) {
                                        $location.search('zoom', evt.level);

                                        $scope.showMapScale(evt);
                                        $scope.$apply();
                                        $scope.updateVisEye();
                                        if ($("#printPreviewContainer").hasClass("active")) {
                                            $scope.currentMapScale = $scope.map.getScale().toFixed(0);
                                            $scope.pRatio = $('#userMapScale').val() / $scope.currentMapScale;
                                            mapTools.updatePrintPreviewBox($scope);
                                        }
                                    }
                                    $scope.ConvertDDToDMS = function (D, lng) {
                                        return {
                                            dir: D < 0 ? lng ? 'W' : 'S' : lng ? 'E' : 'N',
                                            deg: 0 | (D < 0 ? D = -D : D),
                                            min: 0 | D % 1 * 60,
                                            sec: (0 | D * 60 % 1 * 6000) / 100
                                        };
                                    }

                                    function deg_to_dms(deg) {
                                        var d = Math.floor(deg);
                                        var minfloat = (deg - d) * 60;
                                        var m = Math.floor(minfloat);
                                        var secfloat = (minfloat - m) * 60;
                                        var s = Math.round(secfloat);
                                        // After rounding, the seconds might become 60. These two
                                        // if-tests are not necessary if no rounding is done.
                                        if (s == 60) {
                                            m++;
                                            s = 0;
                                        }
                                        if (m == 60) {
                                            d++;
                                            m = 0;
                                        }
                                        return ("" + d + ":" + m + ":" + s);
                                    }
                                    $(window).resize(function () {
                                        if (window.innerWidth > 650) {
                                            $scope.stackedFeature = false;
                                            $scope.stackedFeatureStatus = false;
                                        }
                                        if ($scope.lbBtns == "dynamic") {
                                            $scope.resizeLbBtns();
                                        }

                                    });
                                    //this is for ipad orientationchange issue
                                    window.addEventListener('orientationchange', function () {
                                        var originalBodyStyle = getComputedStyle(document.body).getPropertyValue('display');
                                        document.body.style.display = 'none';
                                        setTimeout(function () {
                                            document.body.style.display = originalBodyStyle;
                                        }, 10);
                                    });

                                    // $scope.initToggle = function () {
                                    //     mapFunction.initToggle($scope);
                                    // }

                                    $scope.map.on("pan-start", function (evt) {
                                        $scope.dijitPopup.close(dialog);
                                    });
                                    $scope.map.on("zoom-start", function (evt) {
                                        $scope.dijitPopup.close(dialog);
                                    });

                                    geoLocate = new LocateButton({
                                        map: $scope.map
                                    }, "LocateButton");
                                    geoLocate.startup();

                                    $scope.changeSliderLable = function () {
                                        //var currentLevel = $scope.map.getLevel();
                                        $scope.labels = ['', '73,957,191', '', '', '', '', '', '', '', '', '', ''];
                                        console.log($scope.labels);
                                        $scope.$apply();
                                    }

                                    /**The code below is for reloading disclaimer page,
                                     *when users get there by clicking browser back button.
                                     *Without reloading it, home and locate button on the map will not be displayed. 
                                     **/
                                    window.onhashchange = function () {
                                        var url = document.location.toString();
                                        var urlCheck = url.substring(url.length - 2, url.length);
                                        if (urlCheck == "#/") {
                                            window.location.href = url.substring(0, url.length - 2);
                                        }
                                        //==code for secureSite== 
                                        var urlCheck1 = url.substring(url.length - 5, url.length);
                                        if (urlCheck1 == "login") { window.location.href = url.substring(0, url.length - 7); }
                                        //==end==
                                    }
                                    /**End of the codes for reloading disclaimer page,
                                     *when users get there by clicking browser back button 
                                     **/
                                    var toggle = new BasemapToggle({
                                        map: $scope.map,
                                        basemap: "satellite"
                                    }, "BasemapToggle");
                                    toggle.startup();

                                    $scope.printer = new Print({
                                        map: $scope.map,
                                        //templates: templates,
                                        url: $scope.printServiceUrl
                                    }, "PrintButton");
                                    $scope.printer.startup();

                                    $scope.pcount = 0;
                                    $scope.printTask = new $scope.PrintTask();
                                    $scope.params = new esri.tasks.PrintParameters();
                                    var scalebar = new Scalebar({
                                        map: $scope.map,
                                        scalebarUnit: "dual"
                                    });

                                    $scope.graphicId = 0;

                                    $scope.defSearch1s = [];
                                    $scope.selectedDefSearch1 = null;
                                    $scope.defSearch2s = [];
                                    $scope.selectedDefSearch2 = null;
                                    $scope.defSearch3s = [];
                                    $scope.selectedDefSearch3 = null;


                                    $scope.advSearch1s = [];
                                    $scope.selectedAdvSearch1 = null;
                                    $scope.advSearch2s = [];
                                    $scope.selectedAdvSearch2 = null;
                                    $scope.advSearch3s = [];
                                    $scope.selectedAdvSearch3 = null;
                                    $scope.advSearch4s = [];
                                    $scope.selectedAdvSearch4 = null;
                                    $scope.advSearch5s = [];
                                    $scope.selectedAdvSearch5 = null;
                                    $scope.advSearch6s = [];
                                    $scope.selectedAdvSearch6 = null;

                                    $scope.queryTaskTouches = new $scope.QueryTask(queryTaskTouchesUrl);
                                    $scope.queryTaskTouchesByGraphics = new $scope.QueryTask(queryTaskTouchesUrl);
                                    $scope.queryTaskTouchesNearby = new $scope.QueryTask(queryTaskTouchesUrl);

                                    var addToSearchAhead = new $scope.Query();
                                    //addToSearchAhead.outFields = ["OWN", "ParcelAddress1", "MMAP"];
                                    addToSearchAhead.outFields = $scope.addToSearchAheadOutFields;

                                    $scope.bindGraphicId = function (text, color, type) {
                                        var thisPath = $("#map_layers").find(':contains("' + text + '")');
                                        $scope.graphicId++;
                                    }

                                    //these values are for calling parcelSearch()
                                    $scope.queryTask = new $scope.QueryTask($scope.queryTaskUrl);
                                    $scope.query2 = new $scope.Query();
                                    $scope.query2.outFields = $scope.initParcelFields;
                                    $scope.query2.returnGeometry = true;

                                    dojo.connect($scope.queryTaskTouches, "onComplete", function (fset) { //buffer result
                                        var adjacentFeatures = fset.features;
                                        var adjoinerIds = [];

                                        function geomResults(results) {
                                            //console.log(results);
                                            results = results.features;
                                            var listCt = 0; //alert(results.length);

                                            for (var i = 0; i < results.length; i++) {
                                                var totVal = 0;
                                                if ($scope.sumQueryResultFld.length > 1) {
                                                    for (var k = 0; k < $scope.sumQueryResultFld.length; k++) {
                                                        totVal += parseInt(results[i].attributes[$scope.sumQueryResultFld[k]]);
                                                    }
                                                    results[i].attributes['customTotVal'] = $scope.formatParcelData('customTotVal', totVal, results[i].attributes['customTotVal']);
                                                }




                                                for (var key in results[i].attributes) {
                                                    thisKey = results[i].attributes[key.toString()];
                                                    results[i].attributes[key.toString()] = $scope.formatParcelData(key, thisKey, results[i].attributes[key.toString()]);
                                                    results[i].attributes.geometry = results[i].geometry;
                                                }
                                                if (adjoinerIds.contains(results[i].attributes[$scope.parcelUid]) || $scope.selectedParcel[$scope.parcelUid] == results[i].attributes[$scope.parcelUid]) {
                                                    // console.log("duplicate, not pushing");
                                                } else {
                                                    adjoinerIds.push(results[i].attributes[$scope.parcelUid]);
                                                    // console.log("pushed:"); //console.log(results[i].attributes[$scope.parcelUid]);
                                                    $scope.adjoinerList.push(results[i].attributes);
                                                    $scope.adjoinerList[listCt]['index'] = listCt;
                                                    listCt++;
                                                }
                                            }
                                            //console.log($scope.clearAdjResults);
                                            if (listCt == 0) {
                                                $scope.emptyAdjoiner = true;
                                            }
                                            $scope.$apply();

                                            $("#adjoinerList").css("z-index", 21);
                                            setTimeout($scope.myScroll4.refresh(), 100);
                                        }

                                        var queryGeom = new $scope.QueryTask(queryGeomUrl);
                                        var queryGeometry = new $scope.Query();
                                        queryGeometry.returnGeometry = true;
                                        queryGeometry.outFields = $scope.initParcelFields;

                                        queryGeometry.where = $scope.parcelUid + " IN (";
                                        for (var i = 0; i < adjacentFeatures.length; i++) {
                                            adjacentFeatures[i] = adjacentFeatures[i].attributes;
                                            if (typeof $scope.selectedParcel[$scope.parcelUid] === "string") {
                                                queryGeometry.where += "'" + adjacentFeatures[i][$scope.parcelUid] + "'";
                                            }
                                            else {
                                                queryGeometry.where += adjacentFeatures[i][$scope.parcelUid];
                                            }

                                            if (i < adjacentFeatures.length - 1) {
                                                queryGeometry.where += ",";
                                            }
                                        }
                                        queryGeometry.where += ")";
                                        queryGeom.execute(queryGeometry, geomResults);
                                        if ($scope.immediateAdjoiners == true) { //alert("adjacentFeatures.length:" + adjacentFeatures.length);
                                            if (!adjacentFeatures.length || adjacentFeatures.length < 1) {
                                                $scope.emptyAdjoiner = true;
                                                $("#parcelPreloaderContainer").removeClass("active");
                                                $("#adjoinerList").css("z-index", 21);
                                            } else {
                                                $scope.emptyAdjoiner = false;
                                            }
                                        } else {
                                            if (!adjacentFeatures.length || adjacentFeatures.length < 2) {
                                                $scope.emptyAdjoiner = true;
                                                $("#parcelPreloaderContainer").removeClass("active");
                                                $("#adjoinerList").css("z-index", 21);

                                            } else {
                                                $scope.emptyAdjoiner = false;
                                            }
                                        }
                                        $scope.$apply();
                                    });


                                    dojo.connect($scope.queryTaskTouchesNearby, "onComplete", function (fset) { //nearby buffer result

                                        var adjacentFeatures = fset.features;

                                        function geomResults(results) {
                                            searchResult.showResults($scope, results);
                                        }
                                        if (adjacentFeatures.length < 1) {
                                            alert("No parcels found.");
                                        } else {
                                            var queryGeom = new $scope.QueryTask(queryGeomUrl);
                                            var queryGeometry = new $scope.Query();
                                            queryGeometry.returnGeometry = true;
                                            queryGeometry.outFields = $scope.initParcelFields;

                                            queryGeometry.where = $scope.parcelUid + " IN (";
                                            for (var i = 0; i < adjacentFeatures.length; i++) {
                                                adjacentFeatures[i] = adjacentFeatures[i].attributes;
                                                if (typeof $scope.selectedParcel[$scope.parcelUid] === "string") {
                                                    queryGeometry.where += "'" + adjacentFeatures[i][$scope.parcelUid] + "'";
                                                }
                                                else {
                                                    queryGeometry.where += adjacentFeatures[i][$scope.parcelUid];
                                                }

                                                if (i < adjacentFeatures.length - 1) {
                                                    queryGeometry.where += ",";
                                                }
                                            }
                                            queryGeometry.where += ")";

                                            queryGeom.execute(queryGeometry, geomResults);
                                        }
                                    });
                                    dojo.connect($scope.queryTaskTouchesByGraphics, "onComplete", function (fset) { //searchby graphics result
                                        searchResult.showResults($scope, $location, fset, true);

                                    });

                                    if ($scope.downloadResults == "false" && $scope.clearResults == "false" && $scope.mapMyResults == "false") {
                                        $("#listResults").addClass("listResultTop");
                                    }
                                    if ($scope.multipleCoordinateDisplay == "true") {
                                        $("#cursorLoc").addClass("cursorLocLeft");
                                    }
                                    if ($scope.numOfDefQueryVar == '1') {
                                        //mapContainer, listCont, .detailPanels
                                        $("#mapContainer").addClass("oneQueryTop");
                                        $("#listCont").addClass("oneQueryTop");
                                        $("#detailPanels").addClass("oneQueryTop");
                                    }

                                    $scope.numDqueryField = 1;
                                    $scope.numAqueryField = 1;
                                    while ($("#defSearch" + $scope.numDqueryField.toString()).length) {
                                        $scope.numDqueryField++;
                                    }
                                    while ($("#advSearch" + $scope.numAqueryField.toString()).length) {
                                        $scope.numAqueryField++;
                                    }
                                    $scope.numDqueryField -= 1;
                                    $scope.numAqueryField -= 1;
                                    //console.log($scope.numDqueryField);
                                    //console.log($scope.numAqueryField);
                                    if ($scope.nArrow == 'true') {
                                        $("#northArrow").addClass('active');
                                    }
                                    if ($scope.sliderStyle == 'large') {
                                        $("#mapScale").addClass('active');
                                    }
                                }, 500); //end of setTimeout***
                            }); //end of appConfig
                        }); //end of require

                        $scope.changeAlt = function () {
                            $("#altOption").html(($("#altOption").html() == "and") ? "or" : "and");
                        }

                        $scope.changeLocOption = function () {
                            console.log($("#cursorLocOption").html());
                            $("#cursorLocOption").html(($("#cursorLocOption").html() == "X,Y") ? "DMS" : "X,Y");
                        }
                        $scope.checkOptions = function () {
                            if ($("#advSearchLayer").val().length == 0) { //alert("aa");
                                //$("#advSearchString").val('');
                            }
                        }
                        $scope.closeDialog = function () {
                            $scope.dijitPopup.close(dialog);
                        }
                        $scope.slideNearby = function () {
                            var effect = 'slide';
                            var options = {
                                direction: 'left'
                            };
                            var duration = 500;
                            $('#nearbyOption').toggle(effect, options, duration);
                            $('#nearbyBufferDist').focus();
                        }
                        $('#NearbyExeButton').click(function () {
                            if ($("#nearbyBufferDist").val().length == 0) {
                                alert("Please enter a buffer distance first.");
                            } else {
                                var effect = 'slide';
                                var options = {
                                    direction: 'left'
                                };
                                var duration = 500;
                                $('#nearbyOption').toggle(effect, options, duration);
                                if (navigator.geolocation) {
                                    navigator.geolocation.getCurrentPosition($scope.getLocation, $scope.locationError);
                                } else {
                                    alert("Browser doesn't support Geolocation.");
                                }
                            }
                        });

                        //=========this is for pdf print text align==========
                        var splitRegex = /\r\n|\r|\n/g;
                        jsPDF.API.textEx = function (text, x, y, hAlign, vAlign) {
                            var fontSize = this.internal.getFontSize() / this.internal.scaleFactor;

                            // As defined in jsPDF source code
                            var lineHeightProportion = 1.15;

                            var splittedText = null;
                            var lineCount = 1;
                            if (vAlign === 'middle' || vAlign === 'bottom' || hAlign === 'center' || hAlign === 'right') {
                                splittedText = typeof text === 'string' ? text.split(splitRegex) : text;

                                lineCount = splittedText.length || 1;
                            }

                            // Align the top
                            y += fontSize * (2 - lineHeightProportion);

                            if (vAlign === 'middle')
                                y -= (lineCount / 2) * fontSize;
                            else if (vAlign === 'bottom')
                                y -= lineCount * fontSize;

                            if (hAlign === 'center' || hAlign === 'right') {
                                var alignSize = fontSize;
                                if (hAlign === 'center')
                                    alignSize *= 0.5;

                                if (lineCount > 1) {
                                    for (var iLine = 0; iLine < splittedText.length; iLine++) {
                                        this.text(splittedText[iLine], x - this.getStringUnitWidth(splittedText[iLine]) * alignSize, y);
                                        y += fontSize;
                                    }
                                    return this;
                                }
                                x -= this.getStringUnitWidth(text) * alignSize;
                            }

                            this.text(text, x, y);
                            return this;
                        };
                        //=========end of pdf print text align============


                        $scope.gotoCountyDelay = 0; //to prevent multiple call    
                        $scope.gotoCounty = function (parcelid) {
                            $scope.localCustom.gotoCounty($scope, parcelid);
                        };

                        $scope.locationError = function (error) {
                            parcelSearch.locationError(navigator, error);
                        };
                        $scope.getLocation = function (location) {
                            parcelSearch.getLocation($scope, location);
                        };

                        $("#bufferForm").on("submit", function (formData) {
                            parcelSearch.bufferFormSubmit($scope, $scope.getAdjoiners);
                            return false;
                        });
                        $("#immediateAdjoinersToggle").click(function () {
                            mapTools.immediateAdjoinersToggle($scope, $scope.immediateAdjoiners, $scope.getAdjoiners);
                        });
                        $("#adjoinerDistance").on("input", function (event) {
                            parcelSearch.adjoinerDistanceInput($scope, $scope.lastBufferDistance, $scope.SelectedUnit, $scope.lastBufferUnit, event);
                        });


                        //$("#advSearch3").on("input", function(event){parcelSearch.advAcreageFromInput(event);});
                        //$("#advSearch4").on("input", function(event){parcelSearch.advAcreageToInput(event);});

                        $("#nearbyBufferDist").on("input", function (event) {
                            parcelSearch.nearbyInput(event);
                        });

                        $("#openDrawTools").click(function () {
                            mapTools.openDrawTools($scope);
                        });
                        $("#openLayerSelect").click(function () {
                            mapTools.openLayerSelect($scope);
                        });
                        $("#openBookmarks").click(function () {
                            mapTools.openBookmarks($scope);
                        });
                        $("#openPrintMap").click(function () {
                            mapTools.openPrintMap($scope);
                        });
                        //$("#openLocateTool").click(function(){mapTools.openLocateTool($scope);});
                        $scope.openLocateTool = function () {
                            mapTools.openLocateTool($scope);
                        };
                        $scope.openSelectByGraphic = function (event) {
                            mapTools.openSelectByGraphic($scope, event);
                            //mapTools.activateTool($scope, 'selectByGraphic', event);
                        };
                        $scope.changeDrawingTool = function (targetSource) {
                            mapTools.changeDTool($scope, targetSource);
                            //mapTools.activateTool($scope, 'selectByGraphic', event);
                        };
                        $scope.openSwipeTool = function (event) {
                            mapTools.openSwipeTool($scope, event);
                        };
                        $scope.updateSwipe = function () {
                            mapTools.updateSwipe($scope);
                        };
                        $scope.enableSwipe = function () {
                            mapTools.enableSwipe($scope);
                        };
                        $scope.disableSwipe = function () {
                            mapTools.disableSwipe($scope);
                        };

                        $("#showLineLabels").click(function (event) {
                            mapTools.showLineLabels(event);
                        });
                        $("#showPolygonLabels").click(function (event) {
                            mapTools.showPolygonLabels(event);
                        });
                        $("#freehand").click(function (event) {
                            mapTools.freehand($scope, event);
                        });
                        $("#freehandLine").click(function (event) {
                            mapTools.freehandLine($scope, event);
                        });
                        $("#basemapGalleryButton").click(function () {
                            mapTools.basemapGalleryButton($scope);
                        });
                        $('#mobileBack').on("click touchstart", function () {
                            setTimeout(function () {
                                $scope.hidePanel2();
                            }, 300);
                        });
                        $scope.openReportLinkDelay = 0; //to prevent multiple call
                        $scope.openReportLink = function (linkAttribute) {
                            if ($scope.customReportLink == 'true') {
                                $scope.localCustom.openReportLink($scope, linkAttribute);
                            } else {
                                searchResult.openReportLink($scope, linkAttribute);
                            }
                        };
                        $scope.openReportLinkDelay = 0;
                        $scope.openReportLink_Citation = function () {
                            if (this.result.Citation__ != undefined) {
                                localCustom.openReportLink_Citation($scope, this.result.Citation__);
                            }
                            else {
                                localCustom.openReportLink_Citation($scope);
                            }
                        };
                        $scope.openReportLinkDelay = 0;
                        $scope.openReportLink_Permit = function () {
                            if (this.result.Permit_Number != undefined) {
                                localCustom.openReportLink_Permit($scope, this.result.Permit_Number);
                            }
                            else {
                                localCustom.openReportLink_Permit($scope);
                            }
                        };
                        $scope.numberInput = function (inputId) {
                            parcelSearch.numberInput(inputId);
                        };
                        $scope.showDetail = function () {
                            panelControl.showDetail($scope);
                        };
                        $scope.hideDetail = function () {
                            panelControl.hideDetail();
                        };
                        $scope.hidePanel2 = function () {
                            panelControl.hidePanel2();
                        };
                        $scope.switchParcelDetails = function (value) {
                            panelControl.switchParcelDetails($scope, value);
                        }
                        $scope.showDisclaimer = function () {
                            panelControl.showDisclaimer();
                        };
                        $scope.showP2Delay = 0; //to prevent multiple call    
                        $scope.showP2 = function () {
                            panelControl.showP2($scope);
                        }
                        $scope.refreshIscroll = function () {
                            panelControl.refreshIscroll($scope);
                        }
                        $scope.refreshIscrollAll = function () {
                            panelControl.refreshIscrollAll($scope);
                        }

                        $scope.openImageDelay = 0; //to prevent multiple call
                        $scope.getImages = function (pid, $event) {
                            $scope.parcelImages = [];
                            if ($scope.customImgName == 'true') {
                                $scope.localCustom.getImages($scope, $modal, wlFactory, pid, 1);
                            } else {
                                panelControl.getImages($scope, $modal, wlFactory, pid, 1);
                            }
                        };
                        $scope.findRelatedRecords = function (OBJECTID) {
                            $scope.localCustom.findRelatedRecords($scope, OBJECTID);
                        };
                        $scope.addCustomBasemap = function () {
                            $scope.localCustom.addCustomBasemap($scope);
                        }
                        $scope.openImage = function ($event) {
                            panelControl.openImage($scope, $modal, event);
                        };
                        $scope.openHelp = function () {
                            $rootScope.helpActive = "true";
                            panelControl.openHelp($modal);
                        };
                        $scope.openM1 = function () {
                            panelControl.openM1($scope, $modal);
                        };
                        $scope.openM2 = function () {
                            panelControl.openM2($scope, $modal);
                        };
                        $scope.showSelections = function () {
                            panelControl.showSelections($scope);
                        };
                        $scope.hideSelections = function () {
                            panelControl.hideSelections($scope);
                        };
                        $scope.toggleImg = function (event) {
                            layersUI.toggleImg(event);
                        }

                        $scope.UpdateUnit = function () {
                            parcelSearch.UpdateUnit($scope);
                        };
                        $scope.submitBufferDelay = 0; //to prevent multiple call            
                        $scope.submitBuffer = function () {
                            parcelSearch.submitBuffer($scope);
                        };
                        $scope.newParcel = function (result, panel, layer) {
                            parcelSearch.newParcel($scope, result, panel, layer);
                        };
                        $scope.selectParcelByGraphics = function () {
                            parcelSearch.searchByGraphics($scope)
                        }
                        $scope.formatParcelData = function (key, value, property) {
                            return wlFactory.formatParcelData($scope, key, value, property);
                        }
                        $scope.startDownload = function (format) {
                            createReport.startDownload($scope, format, $timeout);
                        }
                        $scope.exportList = function (format) {
                            createReport.exportList($scope, $timeout);
                        }
                        $scope.switchSearchMode = function ($event) {
                            parcelSearch.switchSearchMode($scope, $event);
                        }
                        $scope.execPrintMap = function () {
                            printMap.execPrintMap($scope);
                        }
                        //$scope.preQueryDefSearch = function(qInput, qid){return wlFactory.preQueryDefSearch($scope, $http, qInput, qid);}                
                        $scope.preQueryDefSearch = function (qInput, qid) {
                            if ($scope.customDefSearchBar == 'true') {
                                return $scope.localCustom.preQueryDefSearch($scope, $http, qInput, qid);
                            } else {
                                return wlFactory.preQueryDefSearch($scope, $http, qInput, qid);
                            }

                        }
                        $scope.preQueryAdvSearch = function (qInput, qid) {
                            if ($scope.customAdvSearchBar == 'true') {
                                return $scope.localCustom.preQueryAdvSearch($scope, $http, qInput, qid);
                            } else {
                                return wlFactory.preQueryAdvSearch($scope, $http, qInput, qid);
                            }

                        }
                        $scope.preQueryItems = function (qInput) {
                            return wlFactory.preQueryItems($scope, $http, qInput);
                        }
                        //$scope.preQueryAdvItems = function(qInput){return wlFactory.preQueryAdvItems($scope, $http, qInput);}
                        $scope.onItemSelect = function ($item) {
                            parcelSearch.search($scope, 'item');
                        }
                        $scope.onAdvItemSelect = function ($item) {
                            parcelSearch.search($scope, 'item');
                        }

                        $scope.updateVisEye = function () {
                            mapFunction.updateVisEye($scope);
                        }
                        $scope.initToggle = function () {
                            mapFunction.initToggle($scope);
                        }
                        $scope.addMap = function () {
                            createReport.addMap($scope, mapUrl);
                        }
                        $scope.onDefSearchSelect = function ($item, qid) {
                            parcelSearch.search($scope, qid);
                        }
                        $scope.searchFromAS = function (qString) {
                            parcelSearch.search($scope, qString);
                        }

                        $scope.activateTool = function (toolType, event) {
                            mapTools.activateTool($scope, toolType, event);
                        }
                        $scope.showList = function (event) {
                            panelControl.showList($scope, event, wlFactory);
                        }
                        $scope.showMap = function (event) {
                            panelControl.showMap($scope, event, wlFactory);
                        }
                        $scope.genParcelInfoBack = function () {
                            panelControl.genParcelInfoBack($scope);
                        }
                        $scope.hideStackDetail = function () {
                            panelControl.hideStackDetail($scope);
                        }
                        $scope.getAdjoiners = function () {
                            parcelSearch.getAdjoiners($scope);
                        }
                        $scope.addGraphic = function (evt) {
                            mapTools.addGraphic($scope, evt);
                        }
                        $scope.zoomToBookmark = function (bookmark) {
                            zoomTo.zoomToBookmark($scope, bookmark);
                        }
                        $scope.zoomToParcel = function (fromMapIt) {
                            zoomTo.zoomToParcel($scope, fromMapIt);
                        }
                        $scope.execGotoXY = function () {
                            zoomTo.execGotoXY($scope);
                        }
                        $scope.clearParcelSearch = function () {
                            mapTools.clearParcelSearch($scope);
                        }
                        $scope.clrBmLyr = function () {
                            zoomTo.clrBmLyr($scope);
                        }
                        $scope.callParcelSearch = function (fromTypeahead, event) {
                            $scope.searchBtn = event.target.id;
                            parcelSearch.search($scope, '');
                        }
                        $scope.toggleOpacity = function (layer, event) {
                            mapTools.toggleOpacity($scope, layer, event);
                        }
                        $scope.showVal = function (layer) {
                            mapTools.showVal($scope, layer);
                        }
                        $scope.showResults = function (results) {
                            searchResult.showResults($scope, $location, results);
                        }
                        $scope.showResults2 = function (results) {
                            searchResult.showResults2($scope, results);
                        }
                        $scope.removeParcel = function (index, panel) {
                            searchResult.removeParcel($scope, index, panel);
                        };
                        $scope.executeIdentifyTask = function ($scope, evt) {
                            layerEvent.executeIdentifyTask($scope, evt);
                        };
                        $scope.openGS = function (evt) {
                            mapTools.openGS($scope, evt);
                        }
                        $scope.openPicto = function (evt) {
                            if ($scope.isCustomEagleView == "true") {
                                localCustom.openPicto($scope, evt);
                            }
                            else {
                                mapTools.openPicto($scope, evt);
                            }

                        }
                        $scope.printComplete = function (result) {
                            printMap.printComplete(result, $scope);
                        }
                        $scope.printError = function (error) {
                            printMap.printError(error, $scope);
                        }
                        $scope.removeAdjParcel = function (index, panel) {
                            searchResult.removeAdjParcel($scope, index, panel);
                        };
                    }); // end of $.getJSON(gisServStrucJsonLink).done(        

            }); //end of $.getJSON('js/mapServUrl.js', function (appConfig) {
        }
    ]); //end of IndexController
})();