angular.module('MobileWebLogistics')
    .service('mapTools', function () {
        var mapToolServ = this;
        //======tool buttons==========//
        this.openPrintMap = function ($scope) {
            $scope.toolbar.deactivate();
            $scope.disableSwipe();
            $("#drawTools div").removeClass("selected").removeClass("unselected");
            if ($("#printMenu").hasClass("active")) {
                $("#printMenu").removeClass("active");
                $("#openPrintMap").removeClass("active");
                $("#printPreviewContainer").removeClass("active");
                $("#printScaleBox").removeClass("printScaleBoxShadow");
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
            } else {
                // Disable keyboard navigation if a user types in the print scale box when it opens
                if ($scope.manualPrintScale == "true" && $scope.map.isKeyboardNavigation === true) {
                    $scope.map.disableKeyboardNavigation();
                }
                $("#mapButtons > div").removeClass("active");
                $("#mapDropdowns > div").removeClass("active");
                $("#printMenu").addClass("active");
                $("#openPrintMap").addClass("active");
                $("#printPreviewContainer").addClass("active");
                $("#printScaleBox").addClass("printScaleBoxShadow");
                $scope.currentMapScale = $scope.map.getScale().toFixed(0);
                this.updatePrintPreviewBox($scope);
                if ($("#printBtn i").attr('class') == 'glyphicon glyphicon-cog gly-spin') {
                    $("#printBtn i").removeClass('glyphicon glyphicon-cog gly-spin').addClass('glyphicon glyphicon-cog gly-spin');
                }
            }
        }

        this.updatePrintPreviewBox = function ($scope) {
            $scope.selPrintSize = $("#printSize").prop('selectedIndex');
            if ($scope.selPrintSize == 0) {
                $scope.rBoxWidth = (610 * $scope.pRatio) + 'px';
                $scope.rBoxHeight = (922 * $scope.pRatio) + 'px';
            } else if ($scope.selPrintSize == 1) {
                $scope.rBoxWidth = (850 * $scope.pRatio) + 'px';
                $scope.rBoxHeight = (684 * $scope.pRatio) + 'px';
            }
            if ($scope.manualPrintScale == "true") {
                document.getElementById("printScaleBox").style.width = $scope.rBoxWidth;
                document.getElementById("printScaleBox").style.height = $scope.rBoxHeight;
            }
        }

        this.openSwipeTool = function ($scope, event) {
            $scope.toolbar.deactivate();

            $("#drawTools div").removeClass("selected").removeClass("unselected");
            if ($("#swipeMenu").hasClass("active")) {
                $("#swipeMenu").removeClass("active");
                $("#openSwipeTool").removeClass("active");
                $scope.disableSwipe();

            } else {
                $(event.target.parentElement).removeClass("selected");
                $("#printPreviewContainer").removeClass("active");
                $("#printScaleBox").removeClass("printScaleBoxShadow");
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#mapButtons > div").removeClass("active");
                $("#mapDropdowns > div").removeClass("active");
                $("#swipeMenu").addClass("active");
                $("#openSwipeTool").addClass("active");
                $scope.enableSwipe();
            }
        }

        this.openSelectByGraphic = function ($scope, event) {
            $scope.toolbar.deactivate();
            $scope.disableSwipe();

            $("#drawTools div").removeClass("selected").removeClass("unselected");
            if ($("#selectByGraphicTool").hasClass("active")) {
                $("#selectByGraphicTool").removeClass("active");
                $("#openSelectByGraphic").removeClass("active");
            } else {
                $(event.target.parentElement).removeClass("selected");
                $("#printPreviewContainer").removeClass("active");
                $("#printScaleBox").removeClass("printScaleBoxShadow");
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#mapButtons > div").removeClass("active");
                $("#mapDropdowns > div").removeClass("active");
                $("#selectByGraphicTool").addClass("active");
                $("#openSelectByGraphic").addClass("active");
            }

            //this.selectByDrawing($scope,'POLYLINE', event);
            this.activateTool($scope, 'selectByGraphic', event);
        }

        //===============
        this.changeDTool = function ($scope, targetSource) {
            // if(targetSource=='select'){
            //     this.clearParcelSearch($scope);
            // }
            var drawTypeList = document.getElementById("selectParcelToolType");
            var drawType = drawTypeList.options[drawTypeList.selectedIndex].value;
            if (freehandCheckSP.checked == true) {
                drawType = "FREEHAND_" + drawType;
            }
            //alert (drawType);
            $scope.toolbar.activate($scope.Draw[drawType]);

        }

        this.updateSwipe = function ($scope) {
            $scope.swipeStyle = $("#swipeStyle").val();
            $scope.swipeStyle = $scope.swipeStyle.replace("string:", "").toLowerCase();

            $scope.swipeBasemap = $("#swipeBasemap").val();
            for (i = 0; i < $("#swipeBasemap")[0].length; i++) {
                if ($scope.swipeBasemap == $("#swipeBasemap")[0][i].value) {
                    $scope.swipeReferenceBasemapTitle = $("#swipeBasemap")[0][i].label;
                    break;
                }
            }
            for (i = 0; i < $scope.basemapGallery.basemaps.length; i++) {
                if ($scope.swipeReferenceBasemapTitle == $scope.basemapGallery.basemaps[i].title) {
                    $scope.swipeReferenceBasemap = $scope.basemapGallery.basemaps[i];
                    break;
                }
            }

            if ($scope.swipeStyle.length > 0 && $scope.swipeReferenceBasemap !== undefined && $scope.swipeBasemap !== "") {
                if ($scope.swipeOn) {
                    var layersToRemove = [];
                    for (var i = 0; i < $scope.map.layerIds.length; i++) {
                        if ($scope.map.layerIds[i].includes("swipeLayer")) {
                            layersToRemove.push($scope.map.layerIds[i]);
                        }
                    }
                    for (var i = 0; i < layersToRemove.length; i++) {
                        var getLayer = $scope.map.getLayer(layersToRemove[i]);
                        $scope.map.removeLayer(getLayer);
                    }
                }

                // Add layers to swipeLayers array. Handle differently depending on service type
                $scope.swipeLayers = [];
                for (var i = 0; i < $scope.swipeBasemaps.length; i++) {
                    if ($scope.swipeBasemaps[i]) {
                        if ($scope.swipeBasemaps[i].title == $scope.swipeReferenceBasemap.title) {
                            for (var j = 0; j < $scope.swipeBasemaps[i].urls.length; j++) {
                                if ($scope.swipeBasemaps[i].urls[j][0] == "ArcGISTiledMapServiceLayer") {
                                    var swipeLayer = new $scope.ArcGISTiledMapServiceLayer($scope.swipeBasemaps[i].urls[j][1], { id: "swipeLayer" + j });
                                }
                                else {
                                    var swipeLayer = new $scope.VectorTileLayer($scope.swipeBasemaps[i].urls[j][1], { id: "swipeLayer" + j });
                                }
                                $scope.swipeLayers.push(swipeLayer);
                            }
                            break;
                        }
                    }
                }

                // Use addLayers and the API will normalize the list. No need to place swipeLayers at specific indexes
                $scope.map.addLayers($scope.swipeLayers);

                if ($scope.swipeOn == true) {
                    $scope.swipeWidget.set("type", $scope.swipeStyle);
                    $scope.swipeWidget.set("layers", $scope.swipeLayers);
                    if (!$scope.swipeWidget.enabled) {
                        $scope.swipeWidget.enable();
                    }
                } else {
                    $scope.swipeOn = true;
                    $scope.swipeWidget = new $scope.LayerSwipe({
                        type: $scope.swipeStyle,
                        map: $scope.map,
                        layers: $scope.swipeLayers
                    }, "swipeDiv");
                    $scope.swipeWidget.startup();
                    try {
                        $scope.enableSwipe();
                    } catch (err) {
                        console.log(err);
                    }
                }

            } else if ($scope.swipeStyle.length == 0 || $scope.swipeReferenceBasemap === undefined || $scope.swipeBasemap === "") {
                try {
                    $scope.disableSwipe();
                } catch (err) {
                    console.log(err);
                }
            }
        }

        this.disableSwipe = function ($scope) {
            if ($scope.swipeWidget) {
                $scope.swipeWidget.disable();
            }
            if ($scope.swipeLayers) {
                for (var k = 0; k < $scope.swipeLayers.length; k++) {
                    $scope.swipeLayers[k].hide();
                }
            }
        }

        this.enableSwipe = function ($scope) {
            if ($scope.swipeWidget && $scope.swipeStyle.length > 0 && $scope.swipeBasemap !== "") {
                $scope.swipeWidget.enable();
                for (var k = 0; k < $scope.swipeLayers.length; k++) {
                    $scope.swipeLayers[k].show();
                }
            }
        }

        //===============
        this.openLocateTool = function ($scope) {
            $scope.toolbar.deactivate();
            $scope.disableSwipe();
            $("#drawTools div").removeClass("selected").removeClass("unselected");
            if ($("#locateTool").hasClass("active")) {
                $("#locateTool").removeClass("active");
                $("#openLocateTool").removeClass("active");
            } else {
                $("#printPreviewContainer").removeClass("active");
                $("#printScaleBox").removeClass("printScaleBoxShadow");
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#mapButtons > div").removeClass("active");
                $("#mapDropdowns > div").removeClass("active");
                $("#locateTool").addClass("active");
                $("#openLocateTool").addClass("active");

            }
        }
        this.openBookmarks = function ($scope) {
            $scope.toolbar.deactivate();
            $scope.disableSwipe();
            $("#drawTools div").removeClass("selected").removeClass("unselected");
            if ($("#bookmarksMenu").hasClass("active")) {
                $("#bookmarksMenu").removeClass("active");
                $("#openBookmarks").removeClass("active");
            } else {
                $("#printPreviewContainer").removeClass("active");
                $("#printScaleBox").removeClass("printScaleBoxShadow");
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#mapButtons > div").removeClass("active");
                $("#mapDropdowns > div").removeClass("active");
                $("#bookmarksMenu").addClass("active");
                $("#openBookmarks").addClass("active");
            }
        }

        this.openDrawTools = function ($scope) {
            $scope.toolbar.deactivate();
            $scope.disableSwipe();
            $("#drawTools div").removeClass("selected").removeClass("unselected");
            if ($("#drawTools").hasClass("active")) {
                $("#drawTools").removeClass("active");
                $("#openDrawTools").removeClass("active");
            } else {
                $("#printPreviewContainer").removeClass("active");
                $("#printScaleBox").removeClass("printScaleBoxShadow");
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#mapButtons > div").removeClass("active");
                $("#mapDropdowns > div").removeClass("active");
                $("#drawTools").addClass("active");
                $("#openDrawTools").addClass("active");
            }
        }

        this.openLayerSelect = function ($scope) {
            $scope.toolbar.deactivate();
            $scope.disableSwipe();
            $("#drawTools div").removeClass("selected").removeClass("unselected");
            if ($("#layerSelect").hasClass("active")) {
                $("#layerSelect").removeClass("active");
                $("#openLayerSelect").removeClass("active");
                $("#basemapGalleryButton").css("opacity", 0.8); //temp solution to init change in android app
            } else {
                $("#printPreviewContainer").removeClass("active");
                $("#printScaleBox").removeClass("printScaleBoxShadow");
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#mapButtons > div").removeClass("active");
                $("#mapDropdowns > div").removeClass("active");
                $("#layerSelect").addClass("active");
                $("#openLayerSelect").addClass("active");
                $("#basemapGalleryButton").css("opacity", 0.75); //temp solution to init change in android app    
            }
        }

        this.activateTool = function ($scope, toolType, event) {
            if (event.target.tagName != "DIV" || $(event.target).hasClass("toolButton")) {
                event.target = $(event.target).parent();
            }
            if ($(event.target).hasClass("selected")) {
                $scope.toolbar.deactivate();
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#drawTools .unselected").removeClass("unselected");
                $("#drawTools .selected").removeClass("selected");
                if (toolType == 'identify') {
                    $("#identifyButton").removeClass("selected");
                    $("#iImage").attr('src', "img/ilayers3.png");
                    //$("#identifyButton").css('background','#666666');
                    $("#identifyButton").removeClass("identifyActive");
                    $scope.map.infoWindow.hide();
                    $scope.searchTarget = 'parcels';
                    $("#map_container").removeClass("IdentifyCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'pointer');

                } else if (toolType == 'GS') {
                    $("#GSButton").css('background', '#666666');
                    $scope.mapSVClick.remove();
                    $("#GSButton").removeClass("selected");
                    $("#gsimage").attr('src', "img/gs1.png");
                    $("#map_container").removeClass("GSCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'pointer');
                } else if (toolType == 'picto') {
                    $("#pictoButton").css('background', '#666666');
                    $scope.mapSVClick.remove();
                    $("#pictoButton").removeClass("selected");
                    //$("#pictoImage").attr('src', "img/picto_w.png");
                    $("#map_container").removeClass("pictoCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'pointer');
                }
            } else {
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                if ($scope.streetView == 'true') {
                    $("#GSButton").css('background', '#666666');
                    $("#gsimage").attr('src', "img/gs1.png");
                    $("#GSButton").removeClass("selected");
                    $("#map_container").removeClass("GSCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'pointer');
                }
                if ($scope.eagleView == 'true') {
                    $("#pictoButton").css('background', '#666666');
                    //$("#gsimage").attr('src', "img/gs1.png");
                    $("#pictoButton").removeClass("selected");
                    $("#map_container").removeClass("pictoCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'pointer');
                }
                //$('#map_graphics_layer').children('path').removeClass('drawPolygon');
                $("#iImage").attr('src', "img/ilayers3.png");
                $("#identifyButton").removeClass("identifyActive");
                $("#identifyButton").removeClass("selected");
                //$("#identifyButton").css('background','#666666');
                $scope.map.infoWindow.hide();
                $scope.searchTarget = 'parcels';
                $("#map_container").removeClass("IdentifyCursor");
                $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'pointer');
                //$('#map_graphics_layer path').addClass('drawPolygon');    
                //$('#map_graphics_layer path').attr("fill", "rgb(0,0,0)");
                //$('#map_graphics_layer').addClass('drawPolygon');    
                $("#drawTools div").addClass("unselected").removeClass("selected");
                $(event.target).removeClass("unselected").addClass("selected");
                if (toolType == 'POINT' || toolType == 'POLYLINE' || toolType == 'POLYGON') {
                    //console.log($scope.map.drawLayer);
                    $scope.Draw.start = "Click to start drawing"; //console.log($scope.Draw);console.log($scope.toolbar);
                    $scope.toolbar.activate($scope.Draw[toolType]); //FREEHAND_POLYLINE
                    //console.log($scope.map);
                    //$scope.map.graphicsLayer.setRenderer(new SimpleRenderer($scope.highlightSymbol));
                    //$('#map_graphics_layer').children('path').attr('fill-opacity', '0.25');        
                    if (toolType == 'POLYLINE' && $('#freehandLine').prop('checked')) {
                        $scope.toolbar.activate($scope.Draw['FREEHAND_POLYLINE']);
                    } else if (toolType == 'POLYGON' && $('#freehand').prop('checked')) {
                        $scope.toolbar.activate($scope.Draw['FREEHAND_POLYGON']);
                    }
                } else if (toolType == 'TEXT') {
                    $scope.toolbar.deactivate();
                    var mapClick = $scope.map.on("click", function (evt) {
                        if ($("#textTool").hasClass("selected")) {
                            var displayText = $scope.textTool.text;
                            var font = new $scope.Font(
                                $scope.textTool.size + "pt",
                                $scope.Font.STYLE_NORMAL,
                                $scope.Font.VARIANT_NORMAL,
                                $scope.Font.WEIGHT_BOLD,
                                "Helvetica"
                            );
                            var textSymbol = new $scope.TextSymbol(
                                displayText,
                                font,
                                new $scope.Color($scope.textTool.color)
                            );
                            textSymbol.haloColor = new $scope.Color('#000000');
                            textSymbol.haloSize = 1;
                            textSymbol.setOffset(0, 8);
                            $scope.drawLayer.add(new $scope.Graphic(evt.mapPoint, textSymbol, {
                                gId: $scope.graphicId
                            }));
                            $scope.bindGraphicId(displayText);
                        } else {
                            mapClick.remove();
                        }
                    });
                } else if (toolType == 'identify') {
                    $("#map_container").addClass("IdentifyCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/cursor7.cur),default');
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/cursor7.png) 3 1,auto');
                    $scope.searchTarget = 'layers';
                    $("#iImage").attr('src', "img/ilayers4.png");
                    //$("#identifyButton").css('background',$scope.mainColor);
                    $("#identifyButton").addClass('identifyActive');
                    $scope.dijitPopup.close(dialog);
                    $scope.selectedLayer.clear();
                    $scope.toolbar.deactivate();
                    var mapClick = $scope.map.on("click", function (evt) {
                        if ($("#identifyButton").hasClass("selected")) {
                            $("#identifyPreloaderContainer").addClass("active");
                            $scope.executeIdentifyTask($scope, evt);
                        } else {
                            mapClick.remove();
                            $scope.searchTarget = 'parcels';
                        }
                    });
                } else if (toolType == 'GS') {
                    $("#selectByGraphicTool").removeClass("active");
                    $("#openSelectByGraphic").removeClass("active");
                    $("#pictoButton").css('background', '#666666');
                    //$scope.mapSVClick.remove();
                    $("#pictoImage").attr('src', "img/picto_w.png");
                    $("#pictoButton").removeClass("selected");
                    $("#map_container").addClass("GSCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/gsCursor25.cur),default');
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/gsCursor25.png) 12 25,auto');

                    $("#GSButton").css('background', '#46a848');
                    $("#gsimage").attr('src', "img/gs3.png");
                    $scope.toolbar.deactivate();
                    $scope.mapSVClick = $scope.map.on("click", function (evt) {
                        if ($("#GSButton").hasClass("selected")) {
                            $scope.openGS(evt.mapPoint);
                        } else {
                            $scope.mapSVClick.remove();
                        }
                    });
                }
                else if (toolType == 'picto') {
                    //this.openSelectByGraphic($scope);
                    $("#selectByGraphicTool").removeClass("active");
                    $("#openSelectByGraphic").removeClass("active");
                    $("#iImage").attr('src', "img/ilayers3.png");
                    $("#identifyButton").removeClass("identifyActive");
                    $("#identifyButton").removeClass("selected");
                    $("#GSButton").css('background', '#666666'); $("#gsimage").attr('src', "img/gs1.png");
                    $("#GSButton").removeClass("selected"); $("#map_container").removeClass("GSCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'pointer');
                    //$scope.mapSVClick.remove();

                    $("#map_container").addClass("pictoCursor");
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/pictoCursor.cur),default');
                    $("#" + $scope.parcelLayerName + "_layer path").css('cursor', 'url(img/pictoCursor.png) 3 1,auto');

                    $("#pictoButton").css('background', $scope.baseColor);
                    //$("#pictoImage").attr('src', "img/picto.png");
                    $scope.toolbar.deactivate();
                    try {
                        $scope.mapSVClick.remove();
                    }
                    catch (err) {
                        console.log(err.message);
                    }
                    $scope.mapSVClick = $scope.map.on("click", function (evt) {
                        if ($("#pictoButton").hasClass("selected")) {
                            $scope.openPicto(evt.mapPoint);
                        } else {
                            $scope.mapSVClick.remove();
                        }
                    });
                }
                else if (toolType == 'selectByGraphic') {
                    $scope.map.infoWindow.hide();
                    $("#identifyButton").removeClass("identifyActive");
                    $("#identifyButton").removeClass("selected");
                    //var drawTypeList = document.getElementById("selectParcelToolType");
                    var drawTypeList = document.getElementById("selectParcelToolType");
                    //var drawTypeList = event.target;
                    var drawType = drawTypeList.options[drawTypeList.selectedIndex].value;
                    //console.log ("drawType: "+ drawType);
                    if (freehandCheckSP.checked == true) {
                        drawType = "FREEHAND_" + drawType;
                    }
                    $scope.toolbar.activate($scope.Draw[drawType]);
                    //alert (drawTypeList.selectedIndex);
                    //var drawType = drawTypeList.options[drawTypeList.selectedIndex].value;
                    //// var freehand = false;
                    // if ($('#freehandDrawing').prop('checked') == true) {
                    //     if (drawType == "POLYLINE") {
                    //         drawType = "FREEHAND_POLYLINE"
                    //     }
                    //     else {
                    //         drawType = "FREEHAND_POLYGON"
                    //     }
                    // }
                    //console.log (drawType);
                    //$scope.toolbar.activate($scope.Draw[drawType]);                  



                }
                else {
                    $scope.toolbar.deactivate();
                }
                setTimeout(function () {
                    $("#drawTools > div.selected .drawToolOptions").removeClass("unselected").addClass("selected");
                }, 400);
            }
        }

        this.clearParcelSearch = function ($scope) {
            $scope.drawLayerForSelect.clear();
            //$scope.labelLayer.clear();     
            $scope.multiSelectedLayer.clear();
            $scope.multiSelectedLayer.hide();
            $scope.queryResults = [];
            $scope.emptySearch = true;
            $("#clearResultButton").removeClass("showbtn");
            //$scope.$apply();
        }

        this.openGS = function ($scope, event) {
            // $scope.disableSwipe();
            var mapPoint = event;
            var mp = $scope.webMercatorUtils.webMercatorToGeographic(mapPoint);
            var url = "https://maps.google.com/maps?q=&layer=c&cbll=" + mp.y + "," + mp.x + "&cbp=11,0,0,0,0&ll=" + mp.y + "," + mp.x + "&z=10";
            //var url = "http://localhost/williamsburg/testgskey.html?lat="+mp.y+"&lng="+mp.x;
            //var url = "https://maps.google.com/maps?q=&layer=c&cbll="+lon+","+lat+"&cbp=12,295,0,0,0&ll="+lon+","+lat+"&z=10";
            //var url = "https://maps.google.com/maps?q=&layer=c&cbll=101+Jamestowm+Rd,+williamsburg+va&cbp=11,0,0,0,0&ll=101+Jamestowm+Rd,+williamsburg+va&z=10";

            window.open(url, '_blank');
        }
        this.openPicto = function ($scope, event) {
            // $scope.disableSwipe(); 
            var mapPoint = event;
            var mp = $scope.webMercatorUtils.webMercatorToGeographic(mapPoint);
            //var url = "pictometry/example.aspx?y="+mp.y+"&x="+mp.x;	      
            var url = "pictometry/picto.aspx?y=" + mp.y + "&x=" + mp.x + "&title=" + $scope.navSubSet1 + "&clr=" + $scope.baseColor.replace('#', '') + "&logo=" + $scope.navLogo;
            //alert(url);
            window.open(url, '_blank');
        }
        //=======draw tools=========//        
        this.showLineLabels = function (event) {
            if (event.target.checked) {
                $('#label_layer').attr("style", "opacity: 1");
            } else {
                $('#label_layer').attr("style", "opacity: 0");
            }
        }

        this.showPolygonLabels = function (event) {
            if (event.target.checked) {
                $('#label_layer').attr("style", "opacity: 1");
            } else {
                $('#label_layer').attr("style", "opacity: 0");
            }
        }
        this.freehand = function ($scope, event) {
            if (event.target.checked) {
                $scope.toolbar.activate($scope.Draw['FREEHAND_POLYGON']);
                $('#snapTxt').attr("style", "text-decoration: line-through");
            } else {
                $scope.toolbar.activate($scope.Draw['POLYGON']);
                $('#snapTxt').attr("style", "text-decoration: none");
            }
        }
        this.freehandLine = function ($scope, event) {
            if (event.target.checked) {
                $scope.toolbar.activate($scope.Draw['FREEHAND_POLYLINE']);
                $('#snapLineTxt').attr("style", "text-decoration: line-through");
            } else {
                $scope.toolbar.activate($scope.Draw['POLYLINE']);
                $('#snapLineTxt').attr("style", "text-decoration: none");
            }
        }
        this.addGraphic = function ($scope, evt) {
            var symbol2;
            var areaService = new $scope.GeometryService($scope.geometryServiceUrl);
            areaService.on("areas-and-lengths-complete", outputArea);
            var lengthService = new $scope.GeometryService($scope.geometryServiceUrl);
            lengthService.on("lengths-complete", outputLength);
            var areasAndLengthParams = new $scope.AreasAndLengthsParameters();
            var lengthParams = new $scope.LengthsParameters();
            if ($scope.SelectedLineUnit == "Feet" || $scope.SelectedLineUnit == "Miles") {
                areasAndLengthParams.lengthUnit = $scope.GeometryService.UNIT_FOOT;
                lengthParams.lengthUnit = $scope.GeometryService.UNIT_FOOT;
            } else if ($scope.SelectedLineUnit == "Meters") {
                areasAndLengthParams.lengthUnit = $scope.GeometryService.UNIT_METER;
                lengthParams.lengthUnit = $scope.GeometryService.UNIT_METER;
            }

            if ($scope.SelectedPolygonUnit == "Square Feet") {
                areasAndLengthParams.areaUnit = $scope.GeometryService.UNIT_SQUARE_FEET;
            } else if ($scope.SelectedPolygonUnit == "Acres") {
                areasAndLengthParams.areaUnit = $scope.GeometryService.UNIT_ACRES;
            }

            areasAndLengthParams.calculationType = "preserveShape";

            lengthParams.geodesic = true;
            // This used to be 'preserveShape' but the calculations between ArcMap and our app were incorrect. Updated to planar
            // There was still an issue using planar. preserveShape is not what we want. Updating to geodesic to make it match the area calculations

            // 7/8/19 - This was reverted back to preserveShape. It would be the most accurate representation of a line or area on a curved surface.
            // With ArcGIS Server 10.6, you are unable to calculate area using a geodesic calculation type.
            // preserveShape and geodesic are closely related where planar does not consider the Earth's curvature.
            lengthParams.calculationType = 'preserveShape';

            if (evt.geometry.type == "polygon") {
                areaService.simplify([evt.geometry], function (simplifiedGeometries) {
                    areasAndLengthParams.polygons = simplifiedGeometries;
                    areaService.areasAndLengths(areasAndLengthParams);
                });
                // if($("#openSelectByGraphic").hasClass("active")){
                //     $scope.shapeTool.color="#ed5615";
                // }
                var fillColor = new $scope.Color($scope.shapeTool.color);
                fillColor.a = $scope.shapeTool.fillOpacity / 100;
                if ($("#openSelectByGraphic").hasClass("active") != true) {
                    symbol2 = new $scope.SimpleFillSymbol(
                        $scope.SimpleFillSymbol.STYLE_SOLID,
                        new $scope.SimpleLineSymbol(
                            $scope.SimpleLineSymbol.STYLE_SOLID,
                            $scope.Color.fromHex($scope.shapeTool.color),
                            $scope.shapeTool.thickness
                        ),
                        fillColor
                    );
                }
                else {
                    var drawColor = "#ed5615";
                    fillColor = new $scope.Color(drawColor);
                    fillColor.a = $scope.shapeTool.fillOpacity / 100;
                    symbol2 = new $scope.SimpleFillSymbol(
                        $scope.SimpleFillSymbol.STYLE_SOLID,
                        new $scope.SimpleLineSymbol(
                            $scope.SimpleLineSymbol.STYLE_SOLID,
                            $scope.Color.fromHex(drawColor),
                            $scope.shapeTool.thickness
                        ),
                        fillColor
                    );
                }
            } else if (evt.geometry.type == "polyline") {
                lengthService.simplify([evt.geometry], function (simplifiedGeometries) {
                    lengthParams.polylines = simplifiedGeometries;
                    lengthService.lengths(lengthParams);
                });
                // if($("#openSelectByGraphic").hasClass("active")){
                //     $scope.lineTool.color="#ed5615";
                // }
                if ($("#openSelectByGraphic").hasClass("active") != true) {
                    symbol2 = new $scope.SimpleLineSymbol(
                        $scope.SimpleLineSymbol.STYLE_SOLID,
                        $scope.Color.fromHex($scope.lineTool.color),
                        $scope.lineTool.thickness
                    );
                }
                else {
                    var drawColor = "#ed5615";
                    symbol2 = new $scope.SimpleLineSymbol(
                        $scope.SimpleLineSymbol.STYLE_SOLID,
                        $scope.Color.fromHex(drawColor),
                        $scope.lineTool.thickness
                    );
                }
            } else if (evt.geometry.type == "point") {
                //lengthService.simplify([evt.geometry], function(simplifiedGeometries) {
                //lengthParams.polylines = simplifiedGeometries;
                //lengthService.lengths(lengthParams);
                //});
                symbol2 = new $scope.SimpleMarkerSymbol();
                symbol2.setColor($scope.Color.fromHex($scope.pointTool.color));
                symbol2.setStyle($scope.SimpleMarkerSymbol.STYLE_CIRCLE);
                symbol2.setSize($scope.pointTool.size);
                symbol2.setOutline(new $scope.SimpleLineSymbol($scope.SimpleLineSymbol.STYLE_SOLID, $scope.Color.fromHex($scope.pointTool.color), 1));
            }

            var graphic = new $scope.Graphic(evt.geometry, symbol2, {
                gId: $scope.graphicId
            });
            if ($("#openSelectByGraphic").hasClass("active") != true) {
                $scope.drawLayer.add(graphic);
                if (evt.geometry.type == "point") {
                    $scope.graphicId++;
                } //increase gid for next
            }
            else {
                $scope.drawLayerForSelect.add(graphic);
            }

            function outputArea(evtObj) {
                var totalArea = evtObj.result.areas[0];
                if ($scope.SelectedPolygonUnit == "Acres") {
                    totalArea = Math.round(totalArea * 100) / 100;
                } else {
                    totalArea = Math.round(totalArea);
                }
                var displayText = totalArea + " " + $scope.SelectedPolygonUnit;
                var color = $("#shapeToolColor").css("color");
                var matchColors = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;
                var match = matchColors.exec(color);
                match = $scope.rgbToHex(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));
                var font = new $scope.Font(
                    $scope.textTool.size + "pt",
                    $scope.Font.STYLE_NORMAL,
                    $scope.Font.VARIANT_NORMAL,
                    $scope.Font.WEIGHT_BOLD,
                    "Helvetica"
                );
                var textSymbol = new $scope.TextSymbol(
                    displayText,
                    font,
                    new $scope.Color('#FFFFFF')
                );
                textSymbol.haloColor = new $scope.Color('#000000');
                textSymbol.haloSize = 1;
                textSymbol.setOffset(0, 8);
                if ($("#openSelectByGraphic").hasClass("active") != true) {
                    $scope.labelLayer.add(new $scope.Graphic(evt.geometry.getExtent().getCenter(), textSymbol, {
                        gId: $scope.graphicId
                    }));
                    $scope.bindGraphicId(displayText, match, 'polygon');
                }
            }

            function outputLength(evtObj) {
                var totalLength = evtObj.result.lengths[0];
                if ($scope.SelectedLineUnit == "Miles") {
                    totalLength = (totalLength / 5280).toFixed(4);
                    totalLength = Math.round(totalLength * 100) / 100;
                } else {
                    totalLength = Math.round(totalLength);
                }
                var displayText = totalLength + " " + $scope.SelectedLineUnit;
                var font = new $scope.Font(
                    $scope.textTool.size + "pt",
                    $scope.Font.STYLE_NORMAL,
                    $scope.Font.VARIANT_NORMAL,
                    $scope.Font.WEIGHT_BOLD,
                    "Helvetica"
                );
                var textSymbol = new $scope.TextSymbol(
                    displayText,
                    font,
                    new $scope.Color("#" + $scope.textTool.color)
                );
                textSymbol.haloColor = new $scope.Color('#000000');
                textSymbol.haloSize = 1;
                textSymbol.setOffset(0, 8);
                if ($("#openSelectByGraphic").hasClass("active") != true) {
                    $scope.labelLayer.add(new $scope.Graphic(evt.geometry.getExtent().getCenter(), textSymbol, {
                        gId: $scope.graphicId
                    }));
                    $scope.bindGraphicId(displayText, null, 'line');
                }
            }
        }

        //========basemapGallery========//        
        this.basemapGalleryButton = function ($scope) {
            if ($("#basemapGallery").hasClass("active")) {
                $("#basemapGallery").removeClass("active");
                $("#basemapGalleryButton").css("opacity", 0.8);
            } else {
                // Enable keyboard navigation if a user types in the print scale box when it closes
                if ($scope.map.isKeyboardNavigation === false) {
                    $scope.map.enableKeyboardNavigation();
                }
                $("#basemapGallery").addClass("active");
                $("#basemapGalleryButton").css("opacity", 0.25);
            }
        }

        //========ToggleUI========//        
        this.showVal = function ($scope, layer) {
            var lname = layer.substring(0, layer.length - 12); //-Transparency           
            var lyrOpacity = $("#" + layer).val();
            if (lname == "baseMap") {
                //lname="map_layer0";
                lname = $("#map_layers :first-child").attr('id');

                $("#" + lname).css("opacity", lyrOpacity / 100);
            } else if (lname == "overlay") {
                if ($scope.isFeatureService) {
                    setTimeout(function () {
                        for (var i = 0; i < $scope.checkboxList.length; i++) {
                            if (document.getElementById($scope.checkboxList[i][0] + "Check").checked) { //checked	
                                if ($scope.checkboxList[i][0] != $scope.parcelLayerName) {
                                    // var layer = $scope.map.getLayer("coreService_" + $scope.checkboxList[i][1]);
                                    var layer = $scope.map.getLayer($scope.checkboxList[i][0].replaceAll("_", " "));
                                    layer.setOpacity(lyrOpacity / 100);
                                }
                            }
                        }
                    }, 500);
                }
                else {
                    $scope.dmsLayer.setOpacity(lyrOpacity / 100);
                    // lname = "map_layer1";
                    // $("#" + lname).css("opacity", lyrOpacity / 100);
                }
            } else {
                $("#" + lname + "_layer").css("opacity", lyrOpacity / 100);
                if ("#" + lname + "labels_layer") {
                    $("#" + lname + "labels_layer").css("opacity", lyrOpacity / 100);
                }
            }
        }

        this.toggleOpacity = function ($scope, layer, event) {
            $scope.onList = [];
            if ((layer == $scope.parcelLayerName + 'Transparency') || (layer == 'baseMapTransparency')) {
                if (event.target.checked) {

                    $(event.target).parent().parent().css("opacity", "1").css("pointer-events", "auto");
                    if (layer == 'baseMapTransparency') {
                        $("#map_layers > div:first-child").css("display", "block");
                    } else {
                        var lid = $scope.parcelLayerName + "_layer";
                        $("#" + lid).css("visibility", "visible");
                        $("#" + lid).css("opacity", $("#" + layer).val() / 100);
                        $scope.map.getLayer($scope.parcelLayerName).show();
                    }
                } else {
                    if (layer == 'baseMapTransparency') {
                        $("#map_layers > div:first-child").css("display", "none");
                    } else {
                        $("#" + $scope.parcelLayerName + "_layer").css("visibility", "hidden");
                        $scope.map.getLayer($scope.parcelLayerName).hide();
                    }
                }
            } else {

                if ($scope.isFeatureService) {
                    var visible = event.target.checked;
                    var layerName = event.target.id.replace("Check", "");
                    for (var i = 0; i < $scope.checkboxList.length; i++) {
                        if ($scope.checkboxList[i][0] == layerName) {
                            // var mapLayer = $scope.map.getLayer("coreService_"+$scope.checkboxList[i][1]);
                            var mapLayer = $scope.map.getLayer($scope.checkboxList[i][0].replaceAll("_", " "));
                            var lyrOpacity = $("#overlayTransparency").val();
                            mapLayer.setOpacity(lyrOpacity / 100);
                            mapLayer.setVisibility(visible);
                            break;
                        }
                    }
                }
                else {
                    for (var i = 0; i < $scope.checkboxList.length; i++) {
                        if ($("#" + $scope.checkboxList[i][0] + "Check").is(':checked')) { //alert($scope.checkboxList[i][0]);            
                            var vislyr = $scope.checkboxList[i][1]; //total number of layers in the service - layerId, because of the wms(backward) 

                            if ($scope.checkboxList[i][0] != $scope.parcelLayerName.replaceAll(" ", "_")) {
                                $scope.onList.push(vislyr);
                            }
                        }
                    }
                    $scope.dmsLayer.setVisibleLayers($scope.onList);
                }
            }
        }

        this.extentHistoryChangeHandler = function ($scope) {
            if ($scope.navToolbar.isFirstExtent()) {
                $("#previousBtnImg").removeClass("navActive");
            } else {
                $("#previousBtnImg").addClass("navActive");
            }
            if ($scope.navToolbar.isLastExtent()) {
                $("#nextBtnImg").removeClass("navActive");
            } else {
                $("#nextBtnImg").addClass("navActive");
            }
        }

        this.immediateAdjoinersToggle = function ($scope, immediateAdjoiners, getAdjoiners) {
            if ($scope.immediateAdjoiners == true) {
                $("#customBuffer").addClass("fadeOut");
                $scope.getAdjoiners();
            } else {
                $("#customBuffer").removeClass("fadeOut");
            }
        }
    });