﻿var identifyTask,queryTask, identifyParams, symbol, symbolpt, symbolpoly, symbolline;
var findTask, findParams, searchlayerIds, searchtext, resultFields, searchFields;

////////////////// SHARED FUNCTIONS

function displayGraphic(graphic, zoom, fields) {
    switch (graphic.geometry.type) {
        case "point":
            symbol = symbolpt;
            break;
        case "polygon":
            symbol = symbolpoly;
            break;
        case "line":
            symbol = symbolline;
            break;
        case "polyline":
            symbol = symbolline;
            break;
        default: symbol = symbolpoly;
    }
    graphic.setSymbol(symbol);


    //info window
    var strHTML, titleHTML, idResult, attribs;
    titleHTML = "<div style='margin-left: auto; margin-right: auto;height:20px;'>";
    titleHTML += "<div style='float:left;'>Feature Information</div> <div style='float:right;'><a href=# onclick='javascript:map.infoWindow.hide();'>close</a></div><div style='clear: both;'></div></div>";

    // add attributes
    attribs = graphic.attributes;
    strHTML = "<div id='identifyresults'><table id='idAttribs' class='identifyresults' >";
    for (var a in attribs) {
        strHTML += customClientlink(a, attribs[a])
        //alert(customClientlink(a, attribs[a]));
        //match attribute fields to resultfields.  If they match, then display the attribute:
        for (var f in fields) {
            if (fields[f] == 'ALL') // show all the fields   
                if (a.toLowerCase() == "objectid" || a.toLowerCase() == "shape" || a.toLowerCase() == "shape.len")
            { } // do nothing
            else {
                strHTML += "<tr valign='top'><td class='identifyattributes'>" + a + "</td><td class='identifyvalues'>" + attribs[a] + "</td></tr>";
            }
            else if (fields[f].toLowerCase() == a.toLowerCase()) { // show only the matching fields
                strHTML += "<tr valign='top'><td class='identifyattributes'>" + a + "</td><td class='identifyvalues'>" + attribs[a] + "</td></tr>";
            }
        } //end for f
    } //end for a
    strHTML += "</table></div>";
    var infoTemplate = new esri.InfoTemplate();
    infoTemplate.setTitle(titleHTML);
    infoTemplate.setContent(strHTML);
    graphic.setInfoTemplate(infoTemplate);
    map.infoWindow.resize(360, 225);
    map.graphics.add(graphic);

    //if (!graphicInfoWindowHandle)
    if (!graphicInfoWindowHandle)
        graphicInfoWindowHandle = dojo.connect(map.graphics, "onClick", function(evt) {
            //dojo.connect(map.graphics, "onMouseOver", function(evt) {
            var g = evt.graphic;
            map.infoWindow.setContent(g.getContent());
            map.infoWindow.setTitle(g.getTitle());
            map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
        });
    //dojo.connect(map.graphics, "onMouseOut", function() { map.infoWindow.hide(); });

    if (zoom == 'true') {
        switch (graphic.geometry.type) {
            case "point":
                var x = graphic.geometry.x;
                var y = graphic.geometry.y;
                var newpt = new esri.geometry.Point(x, y, new esri.SpatialReference({ wkid: 102113 }));
                //var newpt = selectedfeature.geometry.getExtent().getCenter();
                map.centerAndZoom(newpt, 12)
                break;
            default:
                var newextent = graphic.geometry.getExtent();
                map.setExtent(newextent, true);
                break;
        }
    } //end if zoom
    //RETURN THE ID OF THE JUST ADDED GRAPHIC
    //var graphics = map.graphics.graphics;
    var cnt = map.graphics.graphics.length;
    var graphicid = cnt - 1;
    return graphicid;

} // END displayGraphic

/////////// IDENTIFY FUNCTIONS
function setIdentifyToggle() {
    deactivateTools();
    deactivateStreetView();
    deactivateSearchbyPoly();
    dojo.byId("map_layers").style.cursor = 'crosshair';
    if (!idHandle)
        idHandle = dojo.connect(map, "onClick", doIdentify);
}

function enableIdentify() {
    identifyTask = new esri.tasks.IdentifyTask(REST_Server + mapservice + "/MapServer"); 
    identifyParams = new esri.tasks.IdentifyParameters();
}

function doIdentify(evt) {
   // showLayerLoading();
    showIdentifyBusy(evt.mapPoint.x, evt.mapPoint.y);
    identifyTask = new esri.tasks.IdentifyTask(clientMapService.url);
    map.graphics.clear();
    identifyParams.tolerance = 1;
    identifyParams.returnGeometry = true;
    identifyParams.geometry = evt.mapPoint;
    identifyParams.mapExtent = map.extent;
    identifyParams.height = map.height;
    identifyParams.width = map.width;
    identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;
        
    var layerIds = [];
    var v = dojo.byId("ctl00_ContentPlaceHolder1_hdnLayerids").value.length;
    if (parseInt(v) < 1)
      {identifyParams.layerIds = getLayerIDs("toc");}
      else
      {identifyParams.layerIds = getLayerIDs("database");}
    identifyTask.execute(identifyParams, function(idResults) { addToMap(idResults, evt); }, showIdentifyError);
}

function showIdentifyError(err) {
    hideIdentifyBusy();
    //hideLayerLoading();
    var msg = (err.message != "") ? err.message : err.details[0];
    alert(msg);
}
function showIdentifyBusy(x, y) {
    if (!idBusyGraphic) {
        var busySymbol = new esri.symbol.PictureMarkerSymbol('http://cdn.tierraplan.com/images/loading.gif', 128, 15);
        idBusyGraphic = new esri.Graphic(new esri.geometry.Point(x, y, map.spatialReference), busySymbol);
        busyGraphicsLayer = new esri.layers.GraphicsLayer();
        map.addLayer(busyGraphicsLayer);
    }
    else {
        idBusyGraphic.setGeometry(new esri.geometry.Point(x, y, map.spatialReference));
    }
    busyGraphicsLayer.add(idBusyGraphic);
}

function hideIdentifyBusy() {
    if (idBusyGraphic)
        busyGraphicsLayer.remove(idBusyGraphic);
}

function getLayerIDs(layeroption) {
    layerIDs = [];
    if (layeroption == "database") {
        // option 1) make Identify work for layers defined in admin database
        //a hidden field exists for holding layersids the client wants included in identiy functions.
        var layerIdList = dojo.byId("ctl00_ContentPlaceHolder1_hdnLayerids").value;
        layerIDs.push(layerIdList);
    }
    else {
        // option 2) make Identify work only with layers that are checked on in the layers checkboxes. Layerids come from checkboxes
        var inputs = dojo.query(".checkboxes"), input;
        for (var i = 0, il = inputs.length; i < il; i++) {
            if (inputs[i].checked) {
                layerIDs.push(inputs[i].id);
            }
        }
    }   
    return layerIDs;
}

function addToMap(idResults, evt) {
    currIdResults = idResults;
    var strHTML, titleHTML, idResult, attribs;
    var doclink;
    resultFields = [];
    if (!idResults || idResults.length == 0) {
        strHTML = "<div style='background-color:white;width:95%;'>Sorry, nothing found here. Remember, this function only finds features that are checked in the Layers secton next to the map. </div>";
    }
    else {
        strHTML = "<div id='identifyresults'><table><tr><th colspan=3><b>Layer</b></th></tr>";
        for (var i = 0, il = idResults.length; i < il; i++) {
            idResult = idResults[i];
            attribs = idResult.feature.attributes;

            //1 get the layerid:
            //2 find checkboc control with same layerid
                var cb = dojo.byId('' + idResult.layerId + '');
            //3 get value from checkbox and add to an array, e.g. resultFields = resultField.split(",");
                resultFields = [];
                resultField = cb.value;
                resultFields = resultField.split(",");
               // alert(resultField);
            strHTML += "<tr valign='top'><td><div style='display:inline;'>"
                + "<img id='idAttribImg" + i + "' src='http://cdn.tierraplan.com/images/icons/add.png' onclick='toggleIdAttributes(" + i + ")'>"
                + "<div style='vertical-align:top; display:inline;'>" + idResult.layerName + "</div></div></td>"
                + "<td><a href='#' onclick='showIdFeature(" + i + "," + idResult.layerId + ");return false;'>&nbsp;&nbsp;"
                + "Show</a>"
                + "<td><a href='#' onclick='clearIdFeature(" + i + ");return false;'>&nbsp;&nbsp;"
                + "Clear</a></td>";        
            // add attributes
            strHTML += "<tr><td colspan='4'>"
                + "<table id='idAttribs" + i + "' class='identifyresults' style='display:none;'>";
            for (var a in attribs)
            // 4 match attribute fields to resultfields.  If they match, then display the attribute:
                for (var f in resultFields) {
                    if (resultFields[f] == 'ALL') // show all the fields
                        if (a.toLowerCase() == "objectid" || a.toLowerCase() == "shape" || a.toLowerCase() == "shape.len") {
                        // do nothing
                        }
                        else {
                        // test if attribs[a] starts with http://, if so make it an <a>
                        strHTML += "<tr valign='top'><td class='identifyattributes'>" + a + "</td><td class='identifyvalues'>" 
                            if (attribs[a].indexOf("http://", 0)== 0) {
                             strHTML += "<a href='" + attribs[a] + "' target='_blank'>" + attribs[a] + "</a>"}
                            else { strHTML += attribs[a] }
                        strHTML += "</td></tr>";                    
                    }

                else if (resultFields[f].toLowerCase() == a.toLowerCase()) { // show only the matching fields
                 strHTML += customClientlink(a, attribs[a])  
                 strHTML += "<tr valign='top'><td class='identifyattributes'>" + a + "</td><td class='identifyvalues'>"
                 if (attribs[a].indexOf("http://", 0) == 0) {
                     strHTML += "<a href='" + attribs[a] + "' target='_blank'>" + attribs[a] + "</a>"}
                 else { strHTML += attribs[a] }
                 strHTML += "</td></tr>";      
                }
            }
            strHTML += "</table></td></tr>";
        } //end for loop
        strHTML += "</table></div>";
    }
    titleHTML = "<div style='margin-left: auto; margin-right: auto;height:20px;'>";
    titleHTML += "<div style='float:left;'>Results </div> <div style='float:right;'><a href=# onclick='javascript:map.infoWindow.hide();removeidentifyGraphics();'>close</a></div><div style='clear: both;'></div></div>";
    map.infoWindow.resize(360, 225);
  
    map.infoWindow.setContent(strHTML);
    map.infoWindow.setTitle(titleHTML);
    map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
    hideIdentifyBusy();
    //hideLayerLoading();
}

function showIdFeature(featureNum, cbid) {
    var feature = currIdResults[featureNum].feature;
    var fa = feature.attributes;
    //var identifyshape = fa['Shape'];
    //var cb = dojo.byId('' + cb + '');
    var cb = dojo.byId('' + cbid + '');
    resultFields = [];
    resultField = cb.value;
    resultFields = resultField.split(",");
    //displayGraphic(feature, 'false', resultFields);
    var gid = displayGraphic(feature, 'false', resultFields);
   // alert(gid);
    // add gid to identifyGraphics
    identifyGraphics.push(gid);
}

function clearIdFeature(featureNum) {
    var feature = currIdResults[featureNum].feature;
    map.graphics.remove(feature);
}

function clearIdentify() {
    if (typeof (currIdResults) != "undefined") {
        for (var i = 0, il = currIdResults.length; i < il; i++) {
            var feature = currIdResults[i].feature;
            map.graphics.remove(feature);
        }
    }
}

function toggleIdAttributes(featureNum) {
    var atts = dojo.query("#idAttribs" + featureNum);
    var expand = atts.style("display") == "none";
    var newAttr = (expand) ? "" : "none";
    atts.style("display", newAttr);
    var newImg = (expand) ? "http://cdn.tierraplan.com/images/icons/delete.png" : "http://cdn.tierraplan.com/images/icons/add.png";
    dojo.attr(dojo.byId("idAttribImg" + featureNum), "src", newImg);
}
////////////// END IDENTIFY FUNCTIONS
