// #################################################################################################
//
//  Global Variables:
//      identifyTolerance: Tolerance in map units for the identify tool: This is assigned in initIdentifyFunctionality.
//
//      identifyFooterText: Text at the bottom of the identify callout widget
//      screenEvtPt: this pointer is so that we can refresh the identify widget with the same anchor point
//      idGraphics: Collection of IdentifyFeature graphics captured on the user click.
// functions:
//      doIdentify: Start of the identify process.  Show the working html and then calls the server to do Identify function
//      doIdentify_onComplete: retrieves the results of the IDENTIFYTASK from the server and processes the results
//      showOneIdentify: show the selected identify graphic based on its index in the idGraphics collection
//      identify_error: shows an error when identifying
//      initIdentifyFunctionality: changes the target layer for the identify tool
//
// ####################################################################################################

// this is the task widgets
var identifyTask, identifyParams;
var idLayerOption="top";
var screenEvtPt;

var idGraphics;

var identifyFooterText = "";
var identifyTolerance = 2;

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 orthoDialog = null;
dojo.require("dijits.custom.OrthoIdentifyDialog");

// Layers that have special Identify Functionality
var buildingSketchesLayerName = "Building Sketches";  // "Building Sketches";
var schoolDistrictsLayerName = "School Attendance Districts";
var APZLayerName = "Accident Potential";
var LDNLayerName = "Avg. Sound Levels (Ldn)";
var airportLayerName = "Coastal Carolina Regional Airport";
var floodInsuranceLayerName = "Flood Insurance Rate Maps";
var monumentsLayerName = "Geodetic Monuments";
var parksLayerName = "Recreation Sites";
var schoolsLayerName = "Schools";
var votingSitesLayerName = "Voting Sites";
var orthoGridLayer = "Ortho Boundaries 2007";
var recordSurvey = "Recorded Plat/Map Book";
var trashLayerName1 = "Convenience Sites";
var trashLayerName2 = "Recycle Pickup";
var trashLayerName3 = "Trash Pickup";
var trashLayerName4 = "Hauler Areas";


// ###############################################################
function initIdentifyFunctionality() {
    // called from startup functions.
    identifyTask = new esri.tasks.IdentifyTask(identifyURL);
    identifyParams = new esri.tasks.IdentifyParameters();
    identifyParams.tolerance = identifyTolerance;
    identifyParams.returnGeometry = true;
    identifyParams.layerIds = layersToIdentify;
    identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;
}

function doIdentify(evt) {
    // called from map.js::map_onClick event
    try {
        // 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) { doIdentify_onComplete(idResults, evt); }, identify_error);
    } catch (err) {
    console.debug(err);
    }
}

function identify_error(error) {

    console.debug(error);
    var content = "Error on the page..." + error.message;
    map.infoWindow.setContent(content);
    map.infoWindow.setTitle("");
    map.infoWindow.resize(125, 75);
    map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));

}

function doIdentify_onComplete(idResults, evt) {

    // This function called after the identify Task has returned from the server
    

    idGraphics = [];
    var graphic, topGraphic;
    screenEvtPt = evt.screenPoint;
    var symbol;
    identifyFooterText = "<table><tbody>";
    if (idResults.length > 0) {
        for (var i = 0, il = idResults.length; i < il; i++) {
            var idResult = idResults[i];
            graphic = idResult.feature;
            switch (graphic.geometry.type) {
                case "point":
                    var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 1), new dojo.Color([0, 255, 0, 0.25]));
                    break;
                case "polyline":
                    var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 3);
                    break;
                case "polygon":
                    var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 3);
                    break;
            }

            var s = [];
            s.push("<div class=\"gray\">");
            s.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"95%\"><tbody>");
            s.push("<tr><td class=\"Bar\" width=\"48%\">FieldName</td><td class=\"Bar\">Value</td></tr>");

            var cmd = "";
            var urlLink = "";
            var featureAttributes = graphic.attributes;
            switch (idResult.layerName) {
                case airportLayerName:
                      s.push("<tr>");
                      s.push("<td class='Row2' width='300' height='30' colspan='2'><a href='http://www.newbernairport.com' target=_blank>&nbsp;Press here to open<b><font color=Black> Coastal Carolina Regional Airport's</font></b> web page.</a></td>");
                      s.push("</tr>");
                      break;
                case buildingSketchesLayerName:

                    cmd2 = "showParcel('${PID}', true);"; 
                    s.push("<tr><td class=\"Row1\">Parcel id:</td><td class='Row2' width='100' height='30'><a href=\"#\" onmousedown=\"" + cmd2 + "\">${PID}</a></td></tr>");
                    s.push("<tr>");
                    s.push("<td class='Row1' width='250' height='30'><b>Press button to right for detailed information</b></td>");
                    //
                    //If infoFld = "PARCEL_NUM" and mRecordset.Fields.FieldValueAsString(CLng(f)) <> "1-045   -029" Then
                    //' f1 is attribute field 2 BSEQ
                    //f1 = f + 1
                    //' f2 is attribute field 5 BTYPE
                    //f2 = f + 4
                    
                    cmd = "showBuildingDetails('${PID}',${BSEQ},${BCARD})";
                    
                    s.push("<td class='Row2' width='100' height='30'><a href=\"#\" onmousedown=\"" + cmd + "\"><img src='images/b_details.gif' border='0'></a></td>");
                    //Else
                    //Response.Write "<td class='Row2' width='100' height='30'>&nbsp;</td>"
                    //End If
                    s.push("</tr>");

                    break;
                    
                case cityLayerName:
                    s.push("<tr>");
                    s.push("<td class=\"Row1\" width=\"50%\"  align=\"right\" height=\"30\"><b>CITY:</b></td>");
                    var cityName = featureAttributes["CITYNAME"]
                    switch (cityName) {
                        case "New Bern":
                            urlLink = "http://www.newbern-nc.org";
                            break;
                        case "Havelock":
                            urlLink = "http://www.havelocknc.us";
                            break;
                        case "River Bend":
                            urlLink = "http://www.ci.river-bend.nc.us";
                            break;
                        case "Trent Woods":
                            urlLink = "http://www.trentwoodsnc.org";
                            break;
                        case "Dover":
                            urlLink = "http://www.newbern-nc.org";
                            break;
                        default:
                            urlLink = "";
                            break;
                    }
                    if (urlLink == "")
                        s.push("<td class='Row2' width='200' height='30'>" + cityName + "</td>");
                    else
                        s.push("<td class='Row2' width='200' height='30'><a href=\"" + urlLink + "\" target=\"blank\" >" + cityName + "</a></td></tr>");

                    s.push("</tr>");
                    break;
                case schoolDistrictsLayerName:
                    s.push("<tr>");
                    s.push("<td class=\"Row1\" width=\"50%\"  align=\"right\" height=\"30\"><b>Elementary School:</b></td>");
                    s.push("<td class='Row2' width='200' height='30'><a href=\"" + featureAttributes["ELM_URL"] + "\" target=\"blank\" >" + featureAttributes["Elementary School Name"] + "</a></td></tr>");
                    s.push("</tr>");

                    // middle school
                    s.push("<tr>");
                    s.push("<td class=\"Row1\" width=\"50%\"  align=\"right\" height=\"30\"><b>Middle School:</b></td>");
                    s.push("<td class='Row2' width='200' height='30'><a href=\"" + featureAttributes["MID_URL"] + "\" target=\"blank\" >" + featureAttributes["Middle School Name"] + "</a></td></tr>");
                    s.push("</tr>");
                    
                    // High school
                    s.push("<tr>");
                    s.push("<td class=\"Row1\" width=\"50%\"  align=\"right\" height=\"30\"><b>High School:</b></td>");
                    s.push("<td class='Row2' width='200' height='30'><a href=\"" + featureAttributes["HIG_URL"] + "\" target=\"blank\" >" + featureAttributes["High School Name"] + "</a></td></tr>");
                    s.push("</tr>");
                    
                    
                    break;
                    
                 case orthoGridLayer:
                 
                    
                    if (orthoDialog == null) {
                        orthoDialog = new dijits.custom.OrthoIdentifyDialog();
                        orthoDialog.startup(); }
                        
                    map.infoWindow.hide();
                    
                    orthoDialog.setFeature(graphic);
                    return;

                default:
                    for (att in featureAttributes) {

                        var showIt = true;
                        dojo.forEach(fieldsNotToShow, function(fld) { if (fld.toUpperCase() == att.toUpperCase()) showIt = false });

                        if (showIt) {
                            //console.debug(att);
                            var isSpecial = false;
                            dojo.forEach(specialFields, function(fld) { if (fld.toUpperCase() == att.toUpperCase()) isSpecial = true });


                            var value = featureAttributes[att];
                            if (value == "Null")
                                value = "";


                            if (!isSpecial) {
                                console.debug(att + " is not a special field");
                                s.push("<tr><td class=\"Row1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td><td class=\"Row2\" width=\"50%\" align=\left\">" + value + "<td/></tr>");
                            } else {
                                console.debug("inside the special switch");
                                switch (idResult.layerName) {
                                    case APZLayerName:
                                        if (att.toUpperCase() == "DESCRIPTION") {
                                            s.push("<tr><td class='Row1' width='100' height='30'><b>" + att + "</b></td>");
                                            s.push("<td class='Row2' width='200' height='30'><a href='accident_potential_info.htm' target=_blank> Press here for more information.</a></td>");
                                            s.push("</tr>");
                                        }
                                        break;

                                    case LDNLayerName:
                                                                  
                                        if (att.toUpperCase() == "DESCRIPTION") {
                                            s.push("<tr><td class='Row1' width='100' height='30'><b>" + att + "</b></td>");
                                            s.push("<td class='Row2' width='200' height='30'><a href='noise_info.htm' target=_blank> Press here for more information.</a></td>");
                                            s.push("</tr>");
                                        }
                                        break;
                                    case floodInsuranceLayerName:
                                        // s.push("<tr><td class='Row1' width='100' height='30'><b>Flood Insurance Rate Map:</b></td>");
                                        s.push("<tr><td class=\"Row1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td>");
                                        s.push("<td class=\"Row2\" width=\"50%\" align=\left\">" + value  + "<td/>");
                                        switch (featureAttributes[att]) {
                                            case 4562, 4586, 5583, 6412, 6507, 6516:
                                                //s.push("<td class='Row2' width='200' height='30'>" + value + " A downloadable pdf is not available for this panel.</td>");
                                                 s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>NC Floodmap Site:</b></td>");                                                  
                                                 s.push("<td class='Row2' width='200' height='30'><a href=http://floodmaps.nc.gov/fmis target=_blank>Press here to open site in new window.</a></td></tr>");
                                                 s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>For additional information:</b></td>");
                                                 s.push("<td class='Row2' width='200' height='30'><br>Call the Craven County Planning Dept. at<br>(252) 636-6618</a></td>");                                                                                  
                                                break;
                                            default:
                                                //s.push("<td class='Row2' width='200' height='30'><a href='http://149.168.101.8/dfirm/20/3720" + value + "00E20040702.pdf' target=_blank>&nbsp;Press here to open new window to download FIRM pdf for panel " + value + "</a></td>");
                                                 s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>NC Floodmap Site:</b></td>");                                                  
                                                 s.push("<td class='Row2' width='200' height='30'><a href=http://floodmaps.nc.gov/fmis target=_blank>Press here to open site in new window.</a></td></tr>");
                                                 s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>For additional information:</b></td>");
                                                 s.push("<td class='Row2' width='200' height='30'><br>Call the Craven County Planning Dept. at<br>(252) 636-6618</a></td>");                                               
                                                break;
                                        }
                                        s.push("</tr>");
                                        break;
                                    case monumentsLayerName:
                                        if (att.toUpperCase() == "MONUMENT_P") {
                                            //s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>" + att + "</b></td>");
                                            s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>More Info:</b></td>");
                                            s.push("<td class='Row2' width='200' height='30'><a href='http://www.ncgs.state.nc.us/cgi-bin/ncgsdata.pl?pid=_" + value + "&cnty=d:/geodetic/ncgsweb/search/dat/craven.dat' target=_blank> Press here to open page.</a></td>");
                                            s.push("</tr>");
                                        }
                                        break;
                                    case parksLayerName:
                                        s.push("<tr><td class='Row1' width='100' height='30'><b>" + att + "</b></td>");
                                        s.push("<td class='Row2' width='200' height='30'><a href='" + value + "' target=_blank> Press here to open page.</a></td>");
                                        s.push("</tr>");
                                        break;
                                    case parcelsLayerName:
                                        switch (att.toUpperCase()) {
                                            case "PID":
                                                s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>Parcel ID:</b></td>");
                                                var pin = value
                                                cmd = "showParcel(\"" + pin + "\", true)";
                                                console.debug(cmd);
                                                s.push("<td class=\"Row2\" width=\"200\" height=\"30\"><a href=\"#\" title=\"Show the Parcel\" onmousedown='" + cmd + "'>${PID}</a></td>");
                                                s.push("</tr>");

                                                break;
                                                
                                            //case "EXEMPT":
                                            //   if (value == '')       
                                            //      s.push("<tr><td class=\"Row1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td><td class=\"Row2\" width=\"50%\" align=\left\">No<td/></tr>");
                                            //  else 
                                            //     s.push("<tr><td class=\"Row1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td><td class=\"Row2\" width=\"50%\" align=\left\">Yes<td/></tr>");                                              
                                            //   break; 
                                                                                              
                                            default:

                                                s.push("<tr><td class=\"Row1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td><td class=\"Row2\" width=\"50%\" align=\left\">" + value + "<td/></tr>");
                                                break;
                                        }

                                        break;
                                        

                                    case schoolsLayerName:
                                        if (att.toUpperCase() == "SCHOOL_URL") {
                                            s.push("<tr>");
                                            //s.push("<td class='Row1' width='100' height='30'><b>School URL</b></td>");
                                            //s.push("<td class='Row2' width='200' height='30'><a href='" + featureAttributes[att] + "' target=_blank> Press here to open page.</a></td>");
                                            s.push("<td colspan=\"2\" class=\"Row1\" style=\"text-align:center\"><a href='" + value + "' target=_blank> Press here to open school home page.</a></td>");
                                            s.push("</tr>");
                                        }
                                        break;
                                    //                                    case "School Attendance Districts":          
                                    //                                        var fieldtext = "";          
                                    //                                        switch (att.toUpperCase()) {          
                                    //                                            case "ELM_URL":          
                                    //                                                fieldtext = "Press here to open Elementary School website.";          
                                    //                                                break;          
                                    //                                            case "MID_URL":          
                                    //                                                fieldtext = "Press here to open Middle School website.";          
                                    //                                                break;          
                                    //                                            case "HIGH_URL":          
                                    //                                                fieldtext = "Press here to open High School School website.";          
                                    //                                                break;          
                                    //                                            default:          
                                    //                                                fieldtext = "Press here to open school website";          
                                    //                                                break;          
                                    //                                        }          

                                    //                                        s.push("<tr><td class='Row1' width='100' height='30'><b>" + att + "</b></td>");          
                                    //                                        s.push("<td class='Row2' width='200' height='30'><a href='" + featureAttributes[att] + "' target=_blank>" + fieldtext + " </a></td>");          
                                    //                                        s.push("</tr>");          
                                    //                                        break;           



                                    case votingSitesLayerName:
                                        s.push("<tr>");
                                        s.push("<td class='Row1' width='100' height='30'><b>Craven County Board of Elections Site:</b></td>");
                                        s.push("<td class='Row2' width='200' height='30'><a href='http://www.cravencounty.com/departments/elc.cfm' target=_blank>&nbsp;Press here to open new window</a></td>");
                                        s.push("</tr><tr>");
                                        s.push("<td class='Row1' width='100' height='30'><b>N.C. State Board of Elections Site:</b></td>");
                                        s.push("<td class='Row2' width='200' height='30'><a href='http://www.app.sboe.state.nc.us/pollingplace/precinct.asp?cID=25&pID=" + value + "' target=_blank>&nbsp;Press here to open new window</a></td>");
                                        s.push("</tr>");
                                        break;

                                  case recordSurvey:
                                        if (att.toUpperCase() == "DEEDINFO") {
                                            var deedinfo = featureAttributes["DEEDINFO"];
                                            var dashposition = deedinfo.search("-");
                                            if (dashposition > 0) {
                                              
                                              var deedbook = deedinfo.substr(0,dashposition);
                                              var deedpage = deedinfo.substr(dashposition + 1);
                                              var lengthdeedpage = deedpage.length;
                                              var nonzerofound = 0;                                          
                                              for (var jj=0;jj<lengthdeedpage;jj++) {
                                                 if (nonzerofound == 0) {
                                                   var deedcharacter = deedpage.substr(jj,1);
                                                   if (deedcharacter !== "0") {
                                                     deedpage = deedpage.substr(jj);
                                                     nonzerofound = 1;                                                                                                           
                                                   }
                                                 }  
                                              }     
                                              s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>Plat/Map recorded as Deed Book Page:</b></td>");
                                              s.push("<td class='Row2' width='200' height='30'><a href='http://deeds.cravencounty.com/external/LandRecords/protected/SrchBookPage.aspx?bAutoSearch=true&bk=" + deedbook + "&pg=" + deedpage +"&idx=CRP' target=_blank>Click here to view scanned plat/map.</a></td>");
                                              s.push("</tr>");
                                           }   
                                        }     
                                        break;

                                        case trashLayerName1:
                                        if (att.toUpperCase() == "WASTE_URL") {
                                            s.push("<tr><td class='Row1' width='100' height='30'><b>Craven County Solid Waste & Recycling webpage</b></td>");
                                            s.push("<td class='Row2' width='200' height='30'><a href='http://www.cravencountync.gov/departments/cln.cfm' target=_blank> Click here to open webpage</a></td>");
                                            s.push("</tr>");
                                        }
                                        break;
  
                                        case trashLayerName2:
                                        if (att.toUpperCase() == "WASTE_URL") {
                                            s.push("<tr><td class='Row1' width='100' height='30'><b>Craven County Solid Waste & Recycling webpage</b></td>");
                                            s.push("<td class='Row2' width='200' height='30'><a href='http://www.cravencountync.gov/departments/cln.cfm' target=_blank> Click here to open webpage</a></td>");
                                            s.push("</tr>");
                                        }
                                        break;
                                        
                                        case trashLayerName3:
                                        if (att.toUpperCase() == "WASTE_URL") {
                                            s.push("<tr><td class='Row1' width='100' height='30'><b>Craven County Solid Waste & Recycling webpage</b></td>");
                                            s.push("<td class='Row2' width='200' height='30'><a href='http://www.cravencountync.gov/departments/cln.cfm' target=_blank> Click here to open webpage</a></td>");
                                            s.push("</tr>");
                                        }
                                        break;
                                        
                                        case trashLayerName4:
                                        if (att.toUpperCase() == "WASTE_URL") {
                                            s.push("<tr><td class='Row1' width='100' height='30'><b>Craven County Solid Waste & Recycling webpage</b></td>");
                                            s.push("<td class='Row2' width='200' height='30'><a href='http://www.cravencountync.gov/departments/cln.cfm' target=_blank> Click here to open webpage</a></td>");
                                            s.push("</tr>");
                                        }
                                        break; 
                                                                                                                                                             
                                    default:
                                        

                                        s.push("<tr><td class=\"Row1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td>");
                                        s.push("<td class=\"Row2\" width=\"50%\" align=\left\">" + value  + "<td/></tr>");
                                        break;
                                } // end the switch/case stmt
                            } //  end the special field else
                        }  // end the show it function 
                    } // end the for loop
                    break;
            }   // end the layer switch


            s.push("</tbody></table></div>");

            identifyFooterText = identifyFooterText + "<tr id=\"idf" + i + "\"><td align=\"right\" >" + idResult.layerName + ":</td><td><a href=\"#\" onmousedown=\"showOneIdentify(" + i + ");\" >" + graphic.attributes[idResult.displayFieldName] + "</a></td></tr>";

            // Create template for the info window
            var infoTemplate2 = new esri.InfoTemplate(idResult.layerName, s.join(""));
            graphic.setInfoTemplate(infoTemplate2);

            // set the symbol and add to the map
            graphic.setSymbol(symbol);
            idGraphics.push(graphic);

        }

        identifyFooterText = identifyFooterText + "</tbody></table>";

        showOneIdentify(0);
    } else {

        var content = "No Results Found!";
        map.infoWindow.setContent(content);
        map.infoWindow.setTitle("");
        map.infoWindow.resize(125, 75);
        map.infoWindow.show(screenEvtPt, map.getInfoWindowAnchor(screenEvtPt));
       

    }
}

function showOneIdentify(index) {

    map.graphics.clear();

    var graphic = idGraphics[index];
    console.debug(graphic);

    // 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 {
            var w = 300;
            var h = calloutIdealHeight;
            var dHeight = (map.height / 2) - pointerHeight;

            if (w > (map.width / 2))
                w = (map.width / 2) - 10;

            if (h > dHeight)
                h = dHeight;

            var content = graphic.getContent();
            if (idGraphics.length > 1)
                content = content + identifyFooterText;

            //console.debug(identifyFooterText);

            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(); });

        }
    }
}




