var navigationTool;
var drawPointTool;
var drawPathTool;
var drawPolygonTool;
var modifyTool;
var measureTool;
var highlightTool;
var selectTool;
var navigationHistoryTool;
var infoTool;
var mouseposition;
var graticule;
var overviewmap;
var attribution;

var LegendFloatingPane;

function addTools() {
    // These tools mean the zoom wheel zooms in twice - one in panzoombar and one in navtoolbar.  Need to disable one
    map.addControl(new OpenLayers.Control.PanZoomBar({'zoomWorldIcon': ' true'}));  // Zoom and pan tools
    map.addControl(new OpenLayers.Control.ScaleLine());      // Map scale


    map.addControl(new OpenLayers.Control.Attribution(
    
    { element: $('olControlAttribution') }
    
    ));
   
    map.addControl(new OpenLayers.Control.OverviewMap());    // Overview map

    var overviewOptions = { layers: [wmsClone] };
    overviewmap = new OpenLayers.Control.OverviewMap();
    mouseposition = new OpenLayers.Control.MousePosition({ element: $('olControlMousePosition') });
    mouseposition.displayProjection = new OpenLayers.Projection("EPSG:4326"); 
  
   
    graticule = new OpenLayers.Control.Graticule()
    
    
    
    navigationTool = new OpenLayers.Control.Navigation({ title: "Navigation tool: drag the map to pan left, right, up or down." });
    var zoomBox = new OpenLayers.Control.ZoomBox({ title: "Zoom box: zoom to an area by clicking and drawing a box on the map." });
    drawPointTool = new OpenLayers.Control.DrawFeature(featureLayer, OpenLayers.Handler.Point, { 'displayClass': 'olControlDrawFeaturePoint', title: "Draw point tool: Click on the map to draw a point."});
    drawPathTool = new OpenLayers.Control.DrawFeature(featureLayer, OpenLayers.Handler.Path, { 'displayClass': 'olControlDrawFeaturePath', title: "Draw line tool: Click on the map to draw a line.  Double-click to finish."});
    drawPolygonTool = new OpenLayers.Control.DrawFeature(featureLayer, OpenLayers.Handler.Polygon, { 'displayClass': 'olControlDrawFeaturePolygon', title: "Draw polygon tool: Click on the map to draw a polygon.  Double-click to finish." });
    infoTool = createNewInfoTool();
    modifyTool = new OpenLayers.Control.ModifyFeature(featureLayer, { title: "Modify tool: Click on the feature you want to edit.  Drag the nodes to edit the shape and press 'Delete' when hovering over a node to remove it." });
    

    // Catch drawing events
    featureLayer.events.on({
        "featuremodified": modifyFeature,
        "sketchcomplete": addFeature
    });

    measureTool = createNewMeasureTool();

    navigationHistoryTool = new OpenLayers.Control.NavigationHistory();
    navigationHistoryTool.next.title = "Forwards: move to next map view.";
    navigationHistoryTool.previous.title = "Back: move to previous map view.";
    map.addControl(navigationHistoryTool);

    var panel = new OpenLayers.Control.Panel({ defaultControl: navigationTool });
    panel.addControls([
        navigationTool,
        zoomBox,
        measureTool,
        navigationHistoryTool.next,
        navigationHistoryTool.previous,
        infoTool,
        modifyTool,
        drawPointTool,
        drawPathTool,
        drawPolygonTool
    ]);
    map.addControl(panel);
    map.addControl(graticule);
    map.addControl(mouseposition);
    map.addControl(overviewmap);

    overviewmap.maximizeControl();
   

    // Highlight tool
    highlightTool = new OpenLayers.Control.SelectFeature(featureLayer, {
        hover: true,
        highlightOnly: true,
        multiple: false,
        renderIntent: 'temporary'
    });
    map.addControl(highlightTool);
    highlightTool.activate();

    // Select tool
    selectTool = new OpenLayers.Control.SelectFeature(featureLayer, {
        clickout: true, multiple: false, onSelect: showPopup, onUnselect: closePopup
    });
    map.addControl(selectTool);
    selectTool.activate();

    // Show/hide modify tool
    if (document.getElementById('LoginView1_LoginName1') != null)
        modifyTool.panel_div.style.visibility = 'visible';
    else
        modifyTool.panel_div.style.visibility = 'hidden';

    showDrawingTools(false);
}

function createNewInfoTool() {
	
    var newInfoTool = new OpenLayers.Control.WMSGetFeatureInfo({
        url: 'Handlers/BaseMappingHandler.ashx',
        title: 'Info: click on map features to find related information.',
        queryVisible: true,
        eventListeners: {
            getfeatureinfo: function(event) {
                infoToolResponse(event);
            }
        }	
    });
 
    return newInfoTool;
}

function infoToolResponse(event) {
    if (gPopup != undefined) {
        map.removePopup(gPopup);
        gPopup.destroy();
        gPopup = null;
    }

    if (event.text != "") {
       // alert(event.text);
        if (event.text.indexOf('ServiceException') == -1) {
            gPopup = new OpenLayers.Popup.FramedCloud(
                "Info",
                map.getLonLatFromPixel(event.xy),
                null,
                event.text,
                null,
                true
            );

            map.addPopup(gPopup);
        }
        else
            alert('BETA VERSION: At least one layer currently displayed has not yet been configured so it can be queried.');
    }
}

function createNewMeasureTool() {
    var sketchSymbolizers = {
        "Point": {
            pointRadius: 4,
            graphicName: "square",
            fillColor: "white",
            fillOpacity: 1,
            strokeWidth: 1,
            strokeOpacity: 1,
            strokeColor: "#333333"
        },
        "Line": {
            strokeWidth: 3,
            strokeOpacity: 1,
            strokeColor: "#666666"
        },
        "Polygon": {
            strokeWidth: 2,
            strokeOpacity: 1,
            strokeColor: "#666666",
            fillColor: "white",
            fillOpacity: 0.3
        }
    };
    var style = new OpenLayers.Style();
    style.addRules([
        new OpenLayers.Rule({ symbolizer: sketchSymbolizers })
    ]);
    var styleMap = new OpenLayers.StyleMap({ "default": style });

    var newMeasureTool = new OpenLayers.Control.Measure(
        OpenLayers.Handler.Path, {
            persist: true,
            displaySystem: 'english',
            handlerOptions: {
                layerOptions: { styleMap: styleMap }
            },
            title: "Measure tool: measure distances on the map. Click once to start, double click to finish."
            
        }
    );

    // Add events
    newMeasureTool.events.register('deactivate', '', toggleFloatingPane);
    newMeasureTool.events.register('activate', '', toggleFloatingPane);
    newMeasureTool.events.on({
        "measure": handleMeasurements,
        "measurepartial": handleMeasurements
    });

    return newMeasureTool;
}
var nmi = false;
function toggleMeasureToolUnits(element) {
    try {
        // IE!!!
        

        if (element.srcElement.value == 'english' || element.srcElement.value == 'metric') {
            measureTool.displaySystem = element.srcElement.value;
            nmi = false;
        } else {
        measureTool.displaySystem = 'english';
        nmi = true;
        }
    }
    catch (err) {
        // FF!!!
        measureTool.displaySystem = element.target.value;
    }
}

function toggleFloatingPane() {
    if (dojo.byId("MeasureToolFloatingPane").style.visibility == "hidden")
        MeasureToolFloatingPane.show();
    else
        MeasureToolFloatingPane.hide();
}


function toggleGuidanceDiv() {
//    if (dojo.byId("AddFeatureGuidanceFloatingPane").style.visibility == "hidden")
//        AddFeatureGuidanceFloatingPane.show();
//    else
//        AddFeatureGuidanceFloatingPane.hide();
}

function closeMeasureTool() {
    measureTool.deactivate();
    navigationTool.activate();
    highlightTool.activate();
    selectTool.activate();

}




function toggleMeasureToolGeodesic(element) {
    measureTool.geodesic = element.checked;
}

function handleMeasurements(event) {
    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;

    var element = document.getElementById('measureToolOutput');
   
    var out = "";
    if (nmi) {


        out += "length : " + roundNumber((measure.toFixed(3) * 0.86897624), 3); 

    } else {

    if (order == 1)
        out += "length : " + measure.toFixed(3) + " " + units;
    else
        out += "length : " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
    }
    

    element.innerHTML = out;
}
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}
function toggleLegend() {
    if (dojo.byId("LegendFloatingPane").style.visibility == "hidden")
        LegendFloatingPane.show();
    else
        LegendFloatingPane.hide();
}

function showDrawingTools(visible) {
    if (visible == false) {
        drawPointTool.panel_div.style.visibility = 'hidden';
        drawPathTool.panel_div.style.visibility = 'hidden';
        drawPolygonTool.panel_div.style.visibility = 'hidden';
        drawPointTool.deactivate();
        drawPathTool.deactivate();
        drawPolygonTool.deactivate();
        navigationTool.activate();
    }
    else {
        drawPointTool.panel_div.style.visibility = 'visible';
        drawPathTool.panel_div.style.visibility = 'visible';
        drawPolygonTool.panel_div.style.visibility = 'visible';
        drawPolygonTool.activate();
    }
}

