﻿var pointerHeight = 50;
var goodHeight = 275;

var searchWin;
var screenEvtPt;
var identifyTask, identifyParams;
var idGraphics;
var identifyFooterText = "";
var mTolerance = 1;

var clickMode = "ID";
var idworkingDivHTML = "<div style=\"text-align:center;font-size:1.2em; font-weight:bold;\"><p><img src=\"images/callbackActivityIndicator.gif\" alt=\"please wait\"/></p><p>Please Wait...</p></div>"

var idLayer;
//var mapIDLayers;
var idLayers = [];

var activeLayerInfo = null;
var activeLayerTag = "";

var idPointSymbol, idLineSymbol, idPolygonSymbol;

// ###############################################################
function doIdentify(evt) {

    if (currentTool == "MapIdentify") {

        if (activeLayerTag === "coordinates") {


            // show the info window
            screenEvtPt = evt.screenPoint;
            var content = [];
            content.push("<div class=\"gray\">");
            content.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"90%\"><tbody>");
            content.push("<tr><td class=\"r1\" width=\"50%\" align=\"left\"><b>Easting: </b></td><td class=\"r2\" width=\"50%\" align=\left\">" + Math.round(evt.mapPoint.x, 3) + "</td></tr>");
            content.push("<tr><td class=\"r1\" width=\"50%\" align=\"left\"><b>Northing: </b></td><td class=\"r2\" width=\"50%\" align=\left\">" + Math.round(evt.mapPoint.y, 3) + "</td></tr>");
            content.push("</tbody></table>");
            content.push("</div>");
            map.infoWindow.setContent(content.join(""));
            map.infoWindow.setTitle("Coordinates");
            map.infoWindow.resize(200, 200);
            map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));


            // create the output spatal reference
            var outSpRef = new esri.SpatialReference({ wkid: 4326 });

            var graphic = new esri.Graphic(evt.mapPoint);
            gsvc.project([graphic], outSpRef, function(features) {
                pt = features[0].geometry;

                var dmsx = dijits.util.measure.dd2dms(pt.x);
                var dmsy = dijits.util.measure.dd2dms(pt.y);

                var s = [];
                s.push(content.join(""));
                s.push("<div class=\"gray\">");
                s.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"90%\">");
                s.push("<tr><td class=\"r1\" width=\"50%\" align=\"left\"><b>Latitude:</b></td><td class=\"r2\" width=\"50%\" align=\left\">" + dojo.number.round(pt.y, 3) + "</td></tr>");
                s.push("<tr><td class=\"r1\" width=\"50%\" align=\"left\"><b>Longitude: </b></td><td class=\"r2\" width=\"50%\" align=\left\">" + dojo.number.round(pt.x, 3) + "</td></tr>");
                s.push("<tr><td class=\"r1\" width=\"50%\" align=\"left\"><b>DMS Lat: </b></td><td class=\"r2\" width=\"50%\" align=\left\">" + dmsy.degrees + " " + dmsy.minutes + " " + dmsy.seconds + "</td></tr>");
                s.push("<tr><td class=\"r1\" width=\"50%\" align=\"left\"><b>DMS Long: </b></td><td class=\"r2\" width=\"50%\" align=\left\">" + dmsx.degrees + " " + dmsx.minutes + " " + dmsx.seconds + "</td></tr>");
                s.push("</table>");
                s.push("</div>");

                map.infoWindow.setContent(s.join(""));
                map.infoWindow.setTitle("Coordinates");
                map.infoWindow.resize(200, 200);
                map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));


                
            }, identify_error);
        
        } else {

            hideLoading();

            // show the info window
            screenEvtPt = evt.screenPoint;
            var content = idworkingDivHTML;
            map.infoWindow.setContent(content);
            map.infoWindow.setTitle("");
            map.infoWindow.resize(125, 125);
            map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));

            map.graphics.clear();
            identifyParams.geometry = evt.mapPoint;
            identifyParams.mapExtent = map.extent;
            identifyTask.execute(identifyParams, function(idResults) { identifyTask_onComplete(idResults, evt); }, identify_error);

            
        
        }
    } 
}



function identify_error(error) {

    console.debug(error);
    var content = "Error on the page...";
    map.infoWindow.setContent(content);
    map.infoWindow.setTitle("");
    map.infoWindow.resize(125, 75);
    map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));

}

function initIdentifyFunctionality() {

    // first get the layers in the identify task:
    idLayer = new esri.layers.ArcGISDynamicMapServiceLayer(identifyURL, { id: "identify", visible: false });
    dojo.connect(idLayer, "onLoad", onIdentifyLoaded);
    map.addLayer(idLayer);

    idPointSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 1), new dojo.Color([0, 255, 255], 0.25));
    idLineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([0, 255, 255]), 1);
    idPolygonSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_NONE, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([0, 255, 255]), 2), new dojo.Color([0, 255, 255], 0.25));
    
}

function onIdentifyLoaded() {

         
    var idText = [];
    //idText.push("<ul>");
    idText.push("<div style='margin: 7px 7px 7px'>");
    

    var initialLayer = 0;
    dojo.forEach(idLayer.layerInfos, function(layerinfo) {
        if ((layerinfo.subLayerIds != null) || (layerinfo.parentLayerId == -1)) {

            console.debug(layerinfo.name);

            try {

                if (layerinfo.name == defaultIdentifyLayerName) {
                    activeLayerInfo = layerinfo;
                    idText.push("<input type=\"radio\" name=\"identifyOption\" checked=\"checked\" onClick=\"javascript:changeActiveLayer(" + layerinfo.id + ");\" />");
                } else {
                    idText.push("<input type=\"radio\" name=\"identifyOption\" onClick=\"javascript:changeActiveLayer(" + layerinfo.id + ");\" />");
                }

                idText.push("<label>" + layerinfo.name + "</label><br>");
            } catch (ex) {
                console.error("Error occurred while creating toc element", ex);
            }

        }
    });


    // add coordinates tool
    idText.push("<input type=\"radio\" name=\"identifyOption\" onClick=\"javascript:changeToCoords()\" />");
    idText.push("<label>Get Coordinates</label><br>");

    //idText.push("</ul>");
    idText.push("<div>");
    dojo.byId("identifyLayers").innerHTML = idText.join("");
    changeActiveLayer(activeLayerInfo.id);  
    
}

function changeActiveLayer(indx) {

    try {
        var l = idLayer.layerInfos[indx];
        mapIDLayers = [];
        if (l.subLayerIds != null)
            mapIDLayers = l.subLayerIds;
        else 
            mapIDLayers.push(l.id);
            
        identifyTask = new esri.tasks.IdentifyTask(identifyURL);
        identifyParams = new esri.tasks.IdentifyParameters();
        identifyParams.tolerance = mTolerance;
        identifyParams.returnGeometry = true;
        identifyParams.layerIds = mapIDLayers;
        identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;
        
        dojo.byId("activeLayerTag").innerHTML = l.name;
        activeLayerTag = l.name;
        activeLayerInfo = l;

        hideLoading();
        
    } catch (Error) {
        console.debug(Error);
    }

}

function changeToCoords() {

    activeLayerTag = "coordinates";

}


function updateIdentifyTolerance() {

    mTolerance = dijit.byId("identifyTolerance").getValue();
    identifyTask = new esri.tasks.IdentifyTask(identifyURL);
    identifyParams = new esri.tasks.IdentifyParameters();
    identifyParams.tolerance = mTolerance;
    identifyParams.returnGeometry = true;
    identifyParams.layerIds = mapIDLayers;
    identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;

}

function identifyTask_onComplete(idResults, evt) {
    if (idResults.length == 0) {
        map.graphics.clear();
        map.infoWindow.setContent("No Results Found!!");
        map.infoWindow.setTitle("Location");
        map.infoWindow.resize(200, 200);
        map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));
        dojo.connect(map.infoWindow, "onHide", function() { map.graphics.clear(); });
        return;
    }
       
    idGraphics = [];
    var graphic, topGraphic;
    screenEvtPt = evt.screenPoint;
    var symbol;
    identifyFooterText = "";
    
    
    switch (activeLayerInfo.name) {
        case "dummytest":
            processAll(idResults, evt);
            break;
        default:
            dojo.forEach(idResults, function(graphic) {
                processIdResult(graphic);
            });

            if (idResults.length == 1)
                showOneIdentify(0);
            else
                showMany(idResults);
            
            
            break;
    }

}

function showMany(idResults) {

    identifyFooterText = "";
    if (dojo.isIE)
        identifyFooterText += "<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"90%\">";
    else
        identifyFooterText += "<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"100%\">";

    identifyFooterText += "<tbody>";
        
    dojo.forEach(idResults, function(idResult, i) {
        var graphic = idResult.feature;
        identifyFooterText += "<tr><td>" + idResult.layerName + ":</td><td> <a href=\"#\" onmousedown=\"showOneIdentify(" + i + ");\" >" + graphic.attributes[idResult.displayFieldName] + "</a></td></tr>";
    });

    identifyFooterText += "</tbody></table>";

    var w = 325;
    var h = 200;
    var dHeight = (map.height / 2) - pointerHeight;

    if (h > dHeight)
        h = dHeight;

    map.infoWindow.setContent(identifyFooterText);
    map.infoWindow.setTitle("Results");
    map.infoWindow.resize(w, h);
    map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));
    dojo.connect(map.infoWindow, "onHide", function() { map.graphics.clear(); });

}


function processAll(idResults, evt) {

    var s = [];
    s.push("<div class=\"gray\">");
    if (dojo.isIE)
        s.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"90%\">");
    else
        s.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"100%\">");

    s.push("<tbody>");

    dojo.forEach(idResults, function(idResult) {

        //s.push("<tr><td class=\"titlebar\" colspan=\"2\">" + idResult.layerName + "</td></tr>");

        var graphic = idResult.feature;
        var featureAttributes = graphic.attributes;
        for (att in featureAttributes) {
            s.push("<tr><td class=\"r1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td><td class=\"r2\" width=\"50%\" align=\left\">" + featureAttributes[att] + "</td></tr>");
        }
    });

    s.push("</tbody></table></div>");
   

    var pt = new esri.Graphic(evt.mapPoint);
    pt.setSymbol = idPointSymbol;

    map.graphics.add(pt);

    var w = 325;
    var h = goodHeight;
    var dHeight = (map.height / 2) - pointerHeight;

    if (h > dHeight)
        h = dHeight;

    map.infoWindow.setContent(s.join(""));
    map.infoWindow.setTitle("Results");
    map.infoWindow.resize(w, h);
    map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));
    dojo.connect(map.infoWindow, "onHide", function() { map.graphics.clear(); });
}

function processIdResult(idResult) {

    var graphic = idResult.feature;

    // if parcels
    switch(idResult.layerName){
        case "Parcels":
            graphic.setSymbol(parcelSelectedSymbol);
            var content = dijits.custom.Parcels.getDetails(graphic);
            var infoTemplate = new esri.InfoTemplate(parcels_title_content, content);
            graphic.setInfoTemplate(infoTemplate);
            break;
        default:

            var s = [];
            s.push("<div class=\"gray\">");
            if (dojo.isIE)
                s.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"90%\"><tbody>");
            else
                s.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"100%\"><tbody>");
            s.push("<tr><td class=\"titlebar2\" align=\"right\" width=\"50%\"><b>FieldName</b></td><td class=\"titlebar2\"><b>Value</b></td></tr>");
            
            var featureAttributes = graphic.attributes;
            for (att in featureAttributes) {
                s.push("<tr><td class=\"r1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td><td class=\"r2\" width=\"50%\" align=\left\">" + featureAttributes[att] + "<td/></tr>");
            }
        
            s.push("</tbody></table></div>");
            

            // Create template for the info window
            var infoTemplate2 = new esri.InfoTemplate(idResult.layerName, s.join(""));
            graphic.setInfoTemplate(infoTemplate2);
            

            //point | multipoint | polyline | polygon | extent
            switch (graphic.geometry.type) {
                case "point":
                    graphic.setSymbol(idPointSymbol)
                    break;
                case "line":
                    graphic.setSymbol(idLineSymbol);
                    break;
                case "polygon":
                    graphic.setSymbol(idPolygonSymbol);
                    break;
            }
            break;
    }

    idGraphics.push(graphic);
   
}



function showOneIdentify(index, zoomTo) {

    map.graphics.clear();

    var graphic = idGraphics[index];

    // show the graphic...
    if (graphic != null) {

        map.graphics.add(graphic);

        if (map.height < 300) {
            console.debug("Small map");

            showSidePanel("details-sidebar");
            dojo.byId("details-sidebar-content").innerHTML = graphic.getContent();
            dojo.byId("details-sidebar-header").innerHTML = graphic.getTitle();

        }
        else {
            console.debug(graphic);

            var w = 325;
            var h = goodHeight;
            var dHeight = (map.height / 2) - pointerHeight;

            if (h > dHeight)
                h = dHeight;

            var content = graphic.getContent();
            if (idGraphics.length > 1)
                content =  identifyFooterText + "<hr/>" + content;

            if (zoomTo)
                zoomMap(graphic.geometry);



            map.infoWindow.setContent(content);
            map.infoWindow.setTitle(graphic.getTitle());
            map.infoWindow.resize(w, h);
            map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));
            dojo.connect(map.infoWindow, "onHide", function() { map.graphics.clear(); });

        }
    }

}


function addToSelectionSet(idResults, evt) {

    for (var i = 0, il = idResults.length; i < il; i++) {
        var idResult = idResults[i];
        // if parcels
        if (idResults[i].layerId == parcels_layerID) {
            var idResult = idResults[i];
            graphic = idResult.feature;
            graphic.setSymbol(parcelHighlightSym);

            var content = getParcelContent(graphic);
            var infoTemplate = new esri.InfoTemplate(parcels_title_content, content);
            //Set the infoTemplate.`
            graphic.setInfoTemplate(infoTemplate);

        }
    }

}













