
var smallActivityImgTag = "<img src=\"images/callbackactivityindicator.gif\" alt=\"working\"/>";
var measureToolbar, _measureGraphics;
var _measureHelp, _measureResults;
var _measurePointSymbol, _measureLineSymbol, _measurePolySymbol;

var _measurePtOutSR;

function measureToolbar_startup() {
    try {

        measureToolbar = new esri.toolbars.Draw(map);
        dojo.connect(measureToolbar, "onDrawEnd", measureOnDrawEnd);

        _measureHelp = dojo.byId("measure-context-help");
        _measureResults = dojo.byId("measure-results");

        // create the measure graphics laer
        _measureGraphics = new esri.layers.GraphicsLayer({ id: "measure", displayOnPan: dojo.isIE ? false : true })
        map.addLayer(_measureGraphics);

        _measurePolySymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_CROSS,
                new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 3)
                , new dojo.Color([255, 0, 0]))

        _measureLineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 3);

        _measurePointSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS, 15, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_NONE), new dojo.Color([0, 0, 0]));

        _measurePtOutSR = new esri.SpatialReference({ wkid: 4326 });


        // connect the events to the buttons
        dojo.connect(dojo.byId("b_measure_point"), "onclick", function() { measureToolbar_onMouseDown("point"); });
        dojo.connect(dojo.byId("b_measure_line"), "onclick", function() { measureToolbar_onMouseDown("line"); });
        dojo.connect(dojo.byId("b_measure_poly"), "onclick", function() { measureToolbar_onMouseDown("poly"); });

    } catch (Error) {
        console.warn("An error occurred while activating the measure toolbar", Error);
    }
}


function activateMeasureToolbar() {
    try {
        if (measureToolbar == null) {
            measureToolbar = new esri.toolbars.Draw(map);
        }

        navToolbar.activate(esri.toolbars.Navigation.PAN);
        // reset the mapOnClick event to nothing...

        dojo.byId("b_measure_point").src = "images/b_measure-point_off.png";
        dojo.byId("b_measure_line").src = "images/b_measure-line_off.png";
        dojo.byId("b_measure_poly").src = "images/b_measure-poly_off.png";
        
        _measureResults.innerHTML = "";
        _measureHelp.innerHTML = "";
        map.infoWindow.hide();
        clearCurrentTool();
        changeMapCursors("MapMeasure");

    } catch (Error) {
        console.warn("An error occurred while activating the measure toolbar", Error);
    }
}

function deactivateMeasureToolbar() {

    try {
        if (measureToolbar != null) {
            measureToolbar.deactivate();

            _measureHelp.innerHTML = "";
            _measureResults.innerHTML = "";

            measureToolbar_clear();

        }
    } catch (Error) {
        console.warn("An error occurred while de-activating the measure toolbar", Error);
    }
}

function measureToolbar_clear() {

    try {
        _measureGraphics.clear();
        _measureGraphics.hide();
    } catch (Error) {
        console.warn("An error occurred while de-activating the measure toolbar", Error);
    }

}

function measureToolbar_onMouseDown(name) {

    try {
        console.debug("measuretoolbar on mouse down event triggered: " + name);

        var o = dojo.byId("b_measure_" + name);
        if (o != null) 
            o.src = "images/b_measure-" + name + "_on.png";

        activateMeasureToolbar();
        changeMapCursors("MapMeasure");

        // update context help...
        switch (name) {
            case "point":
                var pointtext = "<div>Click a location on the map.</div>";
                pointtext = pointtext + "<div style=\"margin:5px\">This tool will return a coordinate in: ";
                pointtext = pointtext + "<ul><li>State Plane Feet Coordinates</li><li>Latitude/Longitude Coordinates (Decimal Degrees)</li><ul></div>"
                _measureHelp.innerHTML = pointtext;
                measureToolbar.activate(esri.toolbars.Draw.POINT);
                break;
            case "poly":
                var polytext = "<ul><li>Use the mouse cursor to draw a shape on the map</lli>";
                polytext = polytext + "<li>Click once to start your shape</li>";
                polytext = polytext + "<li>Click once for each subsequent point</li>";
                polytext = polytext + "<li>Double click to end the drawing</li>";
                polytext = polytext + "<li>When the drawing is finished the GIS will calculate the area and display the results below.</li>";
                _measureHelp.innerHTML = polytext;
                measureToolbar.activate(esri.toolbars.Draw.POLYGON);
                break;
            case "line":
                var polytext = "<ul><li>Use the mouse cursor to draw a line on the map</lli>";
                polytext = polytext + "<li>Click once to start your line</li>";
                polytext = polytext + "<li>Click once for each subsequent point</li>";
                polytext = polytext + "<li>Double click to end the drawing</li>";
                polytext = polytext + "<li>When the drawing is finished the GIS will calculate the length and display the results below.</li>";
                _measureHelp.innerHTML = polytext;
                measureToolbar.activate(esri.toolbars.Draw.POLYLINE);
                break;
            default:
                _measureHelp.innerHTML = "";
                break;
        }

    } catch (Error) {
        console.warn("An error occurred setting the measure toolbar the measure toolbar", Error);
    }

}

function measureOnDrawEnd(geometry) {

    try {


        console.debug("inside measureOnDrawEnd Evt");
        console.debug(geometry);

        // create the geometry service
        var gsvc = new esri.tasks.GeometryService(geoServiceUrl);

        // reset the graphics
        _measureGraphics.clear();
        _measureGraphics.show();

        var type = geometry.type;
        if (type === "polygon") {
            var graphic = new esri.Graphic(geometry, _measurePolySymbol);
            _measureGraphics.add(graphic);
            gsvc.simplify([graphic], function(graphics) {
                gsvc.areasAndLengths(graphics, outputAreaAndLength, measureOnGeometryError);
            });
        }

        if (type === "polyline") {
            var graphic = new esri.Graphic(geometry, _measureLineSymbol);
            _measureGraphics.add(graphic);
            gsvc.simplify([graphic], function(graphics) {
                gsvc.lengths(graphics, outputLength, measureOnGeometryError);
            });
        }

        if (type === "point") {

            var graphic = new esri.Graphic(geometry, _measurePointSymbol);
            var pt = graphic.geometry;
            _measureGraphics.add(graphic);

            _measureResults.innerHTML = "<div>X-Coordinate: " + pt.x + "</div><div>Y-Coordinate: " + pt.y + "</div><div><div id=\"latlongcoords\">" + smallActivityImgTag + "</div>";

            gsvc.project([graphic], _measurePtOutSR, function(features) {
                pt = features[0].geometry;
                dojo.byId("latlongcoords").innerHTML = "&nbsp;Latitude: " + dojo.number.round(pt.y, 3) + "<br/>&nbsp;Longitude: " + dojo.number.round(pt.x, 3);
            }, measureOnGeometryError);

        }

    } catch (Error) {
        console.warn("An error occurred in measureOnDrawEnd", Error);

    }

}

function outputLength(result) {

    try {
        var s = [];
        var l = result.lengths[0];
        var mi = l / 5280;
        var meters = l * 0.305;

        s.push("<div style=\"margin:7px\"><p>The length of your line is:<ul>");
        s.push("<li>" + (dojo.number.round(l, 3)) + " feet" + "</li>");
        s.push("<li>" + (dojo.number.round((l / 3), 3)) + " yards" + "</li>");
        s.push("<li>" + (dojo.number.round(meters, 3)) + " meters" + "</li>");
        s.push("<li>" + (dojo.number.round(mi, 3)) + " miles" + "</li>");
        s.push("</ul></div>");

        _measureResults.innerHTML = s.join("");
        showAfterTools();
    } catch (Error) {
        console.warn("An error occurred while retrieving lengths", Error);
    }
}

function outputAreaAndLength(result) {


    try {
        var s = [];
        s.push("<div style=\"margin:7px\"><ul><li>" + dojo.number.round(result.areas[0], 3) + " square feet" + "</li>");
        s.push("<li>" + dojo.number.round(result.lengths[0], 3) + " perimeter feet" + "</li>");

        // acres
        var areaft = result.areas[0];
        var acres = areaft / 43560;

        s.push("<li>" + (dojo.number.round(acres, 3)) + " acres </li>");
        s.push("</ul></div>");

        _measureResults.innerHTML = s.join("");
        showAfterTools();
    } catch (Error) {
        console.warn("An error occurred retrieving measure areas", Error);
    }
}

function measureOnGeometryError(error) {
    try {
        _measureResults.innerHTML = "An Error occurred while retrieving the geometry information from the server...";
        console.warn("An error occurred retrieving measure areas", error);
    } catch (err) {
        console.warn("An error occurred...", err);
    }


}



//var smallActivityImgTag = "<img src=\"images/callbackactivityindicator.gif\" alt=\"working\"/>";
//var measureToolbar;
//function activateMeasureToolbar() {
//    identifyMode = "";
//    dojo.connect(measureToolbar, "onDrawEnd", getMeasures);
//    gsvc = new esri.tasks.GeometryService(geoServiceUrl);
//    dojo.connect(gsvc, "onAreasAndLengthsComplete", outputAreaAndLength);
//    dojo.connect(gsvc, "onLengthsComplete", outputLength);
//}

//function clearMeasureTools() {
//    dojo.byId("measure-results").innerHTML = "";
//    dojo.byId("b_measure_point").src = "images/b_measure-point_off.png";
//    dojo.byId("b_measure_line").src = "images/b_measure-line_off.png";
//    dojo.byId("b_measure_poly").src = "images/b_measure-poly_off.png";
//    dojo.byId("measure-context-help").innerHTML = "";
//}

//function setMeasureToolImage(name) {
//    clearMeasureTools();
//    var o = dojo.byId("b_measure_" + name);
//    if (o != null) 
//        o.src = "images/b_measure-" + name + "_on.png";

//    setClick("");
//    // update context help...
//    var helpnode = dojo.byId("measure-context-help")
//    switch (name) {
//        case "point":
//            var pointtext = "<div>Click a location on the map.</div>";
//            pointtext = pointtext + "<div style=\"margin:5px\">This tool will return a coordinates in: ";
//            pointtext = pointtext + "<ul><li>State Plane Feet Coordinates</li><li>Latitude/Longitude Coordinates (Decimal Degrees)</li><ul></div>"
//            helpnode.innerHTML = pointtext;
//            break;
//        case "poly":
//            var polytext = "<ul><li>Use the mouse cursor to draw a polygon on the map</lli>";
//            polytext = polytext + "<li>Double click to end the drawing</li>";
//            polytext = polytext + "<li>when the drawing is finished the GIS will calculate the area and put the results in the box below.</li>";
//            helpnode.innerHTML = polytext;
//            break;
//        case "line":
//            var polytext = "<ul><li>Use the mouse cursor to draw a line on the map</lli>";
//            polytext = polytext + "<li>Double click to end the drawing</li>";
//            polytext = polytext + "<li>when the drawing is finished the GIS will calulate the length and put the results in the box below.</li>";
//            helpnode.innerHTML = polytext;
//            break;
//        default:
//            helpnode.innerHTML = "";
//            break;
//    }    
//}

//function getMeasures(geometry) {
//    var type = geometry.type;
//    if (type === "polygon") {
//        var graphic = map.graphics.add(new esri.Graphic(geometry, new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_CROSS,
//                new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 3)
//                , new dojo.Color([255, 0, 0]))));
//        gsvc.simplify([graphic], function(graphics) {
//            gsvc.areasAndLengths(graphics);
//        });
//    }

//    if (type === "polyline") {
//        var graphic = map.graphics.add(new esri.Graphic(geometry, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 3)));
//        gsvc.simplify([graphic], function(graphics) {
//            gsvc.lengths(graphics);
//        });
//    }

//    if (type === "point") {
//        var sym = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS, 15, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_NONE), new dojo.Color([0, 0, 0]))

//        var graphic = map.graphics.add(new esri.Graphic(geometry, sym));
//        var pt = graphic.geometry;
//        var outSR = new esri.SpatialReference({ wkid: 4326 });

//        dojo.byId("measure-results").innerHTML = "<div>x-Coord: " + dojo.number.round(pt.x,3) + "</div><div>y-coord: " + dojo.number.round(pt.y,3) + "</div><div><div id=\"latlongcoords\">" + smallActivityImgTag + "</div>";

//        gsvc.project([graphic], outSR, function(features) {
//            pt = features[0].geometry;
//            dojo.byId("latlongcoords").innerHTML = "&nbsp;Latitude: " + dojo.number.round(pt.y, 3) + "<br/>&nbsp;Longitude: " + dojo.number.round(pt.x, 3);
//        });

//    }

//}

//function outputLength(result) {

//    var s = [];
//    var l = result.lengths[0];
//    var mi = l / 5280;
//    var meters = l * 0.305;

//    s.push("<div style=\"margin:7px\"><p>The length of your line is:<ul>");
//    s.push("<li>" + (dojo.number.round(l, 3)) + " feet" + "</li>");
//    s.push("<li>" + (dojo.number.round((l / 3), 3)) + " yards" + "</li>");
//    s.push("<li>" + (dojo.number.round(meters, 3)) + " Meters" + "</li>");
//    s.push("<li>" + (dojo.number.round(mi, 3)) + " Miles" + "</li>");
//    s.push("</ul></div>");

//    dojo.byId("measure-results").innerHTML = s.join("");
//    showAfterTools();
//}

//function outputAreaAndLength(result) {
//    console.log(dojo.toJson(result));
//    var s = [];
//    s.push("<div style=\"margin:7px\"><ul><li>" + result.areas[0] + " square feet" + "</li>");
//    s.push("<li>" + dojo.number.round(result.lengths[0], 3) + " feet" + "</li>");

//    // acres
//    var areaft = result.areas[0];
//    var acres = areaft / 43560;

//    s.push("<li>" + (dojo.number.round(acres, 3)) + " Acres </li>");
//    s.push("</ul></div>");


//    dojo.byId("measure-results").innerHTML = s.join("");
//    showAfterTools();
//}

//function showAfterTools() {
//    dojo.style(dojo.byId("afterMeasureTools"), { "display": "block" });
//}

//function clearMeasureResults() {
//    map.graphics.clear();
//    dojo.style(dojo.byId("afterMeasureTools"), { "display": "none" });
//    dojo.byId("measure-results").innerHTML = "";
//}

//function printMeasureResults() {

//    try {
//        var text = dojo.byId("measure-results").innerHTML;
//        var state = {
//            map: getMapState(map),
//            title: "Area Report",
//            width: 600,
//            height: 600,
//            showlegend: false,
//            legendwidth: 0,
//            legendheight: 0,
//            report: dojo.toJson(text)
//        }

//        var iframeDocument = dojo.isIE ? printingHiddenFrame.contentWindow.document : printingHiddenFrame.contentDocument;
//        iframeDocument.getElementById("appState").value = dojo.toJson(state);
//        iframeDocument.getElementById("form").submit();
//    } catch (err) {
//        dojo.byId("INFO").innerHTML = "<p>There was an error in the application: <br/>" + err.message + "</p>";
//        showPanel("INFO");
//    }
//}

