//provide namespace
dojo.provide("NGCJS.ResultPanel");

//declare new dijit class
dojo.declare("NGCJS.ResultPanel", null, {

    constructor: function(/*HTMLElement*/node, pMap) {

        //apply CSS class to legend
        //dojo.addClass(node, "legend");
        this.domNode = node;

        this.esriMap = pMap;

        //node for each layer's legend
        this._layerNodes = [];

        //this._addLegend = dojo.hitch(this, this._addLegend);
        //this._onLayerReorderHandler = dojo.hitch(this, this._onLayerReorderHandler);
        this._addResults = dojo.hitch(this, this._addResults);

        this.damsCt = 0;
        this.taxMap = "";
    },

    _clearAll: function() {
        this._layerNodes = [];
    },

    _addLayer: function(pLayerName, pLayerId) {
        if (!this._layerNodes[pLayerName]) {
            this._layerNodes[pLayerName] = {
                layerName: pLayerName,
                layerId: pLayerId,
                layerScale: 0,
                recordPage: 0,
                attributes: [],
                records: []
            };
        }
    },

    _addScaleDependentLayer: function(pLayerName, pLayerId, pActiveScale) {
        if (!this._layerNodes[pLayerName]) {
            this._layerNodes[pLayerName] = {
                layerName: pLayerName,
                layerId: pLayerId,
                layerScale: pActiveScale,
                recordPage: 0,
                attributes: [],
                records: []
            };
        }
    },

    _addResults: function(resultJson) {
        //alert("calling add results");
        try {
            //this.domNode
            var layerNodes = this._layerNodes;
            var workingResults;
            if (resultJson.results == undefined) {
                workingResults = resultJson;
            } else {
                workingResults = resultJson.results;
            }
            //domNode.appendChild(document.createTextNode("this is a test"));
            //alert("nodeDAMS: " + layerNodes["DAMS"]);
            dojo.forEach(workingResults, function(layer) {
                //alert(layer.layerName + ": " + layerNodes[layer.layerName]);
                //var damsCk = isDams(layer.layerName);
                var damsCk = false;
                //if (damsCk) {
                //alert("damsck: " + layer.layerName + " | " + layer.feature.attributes["EVENT_ID"]);
                //}
                //
                //alert(layer.layerName + ": " + layer.feature.attributes["EVENT_ID"]);
                if (layerNodes[layer.layerName] != undefined || (layer.feature.attributes["EVENT_ID"] != undefined && layerNodes["Development Activities"] != undefined)) {
                    //alert(layer.layerName + ": passed");
                    //alert("dams? "+layer.layerName.substring(0,4));
                    //alert(layer.layerName+": "+layer.feature.attributes["ACCOUNT"]);
                    if (layer.layerName == "Property" && layer.feature.attributes["ACCOUNT"] == undefined) {

                        //alert("property ck");
                        //if( false ){
                        //
                        propertyList = "";
                        //for (j in layer.feature.attributes) {
                        propertyList = layer.feature.attributes["PROP_ID"];
                        //}
                        // alert("getting property data: "+propertyList);
                        try {
                            console.log("performing search " + searchServiceUrl + "...");
                            esri.request({
                                url: searchServiceUrl,
                                content: {
                                    f: "json",
                                    t: "propid",
                                    v: propertyList
                                },
                                callbackParamName: "callback",
                                load: dojo.partial(resultPanel._addResults),
                                error: function(err) {
                                    console.error("Unable to get view information" + err);
                                }
                            });
                        }
                        catch (e) {
                            console.error(e);
                        }
                    } else if ((layer.layerName == "DAMS" || damsCk) && layer.feature.attributes["EVENT_ID"] == undefined) {

                        //alert("dams ck");

                        propertyList = "";
                        propertyList = layer.feature.attributes["CASE_NUM"];
                        //layerNodes["DAMS"].attributes.push("Loading");
                        //layerNodes["DAMS"].records.push(layer.feature);
                        //alert("getting case data: "+propertyList);

                        //alert("layer: " + layer.layerName + " getting data for case: " + propertyList);

                        try {
                            console.log("performing search " + searchServiceUrl + "...");
                            esri.request({
                                url: searchServiceUrl,
                                content: {
                                    f: "json",
                                    t: "damscase",
                                    v: propertyList
                                },
                                callbackParamName: "callback",
                                load: dojo.partial(resultPanel._addResults),
                                error: function(err) {
                                    console.error("Unable to get view information" + err);
                                }
                            });
                        }
                        catch (e) {
                            console.error(e);
                        }
                    } else {

                        //alert("final ck: ");

                        var tmpLayerName = layer.layerName;
                        if (layer.feature.attributes["EVENT_ID"] != undefined) {
                            tmpLayerName = "Development Activities";
                        }

                        if (layerNodes[tmpLayerName].attributes.length == 0) {
                            // ---------------------------------------------------------------------------
                            // Here we can filter out attributes we don't want to display
                            // ---------------------------------------------------------------------------
                            for (j in layer.feature.attributes) {
                                console.log("j: " + j);
                                // For some reason the index value is not a string, and dijits don't give us access to the js string() cast. So, we cheat with ""+
                                if (j != "OBJECTID" &&
                                        j.toUpperCase() != "OBJECTID_1" &&
                                        j.toUpperCase() != "SHAPE" &&
                                        j.toUpperCase() != "SHAPE.LEN" &&
                                        j.toUpperCase() != "SHAPE_LENGTH" &&
                                        j.toUpperCase() != "SHAPE.LEN" &&
                                        j.toUpperCase() != "SHAPE_AREA" &&
                                        j.toUpperCase() != "SHAPE.AREA" &&
                                        j.toUpperCase() != "GLOBALID") {
                                    layerNodes[tmpLayerName].attributes.push("" + j);
                                }
                            }
                        }
                        //alert("final ck: " + layer.layerName + " | " + layer.feature.attributes["EVENT_ID"]);
                        if (layer.feature.attributes["EVENT_ID"] != undefined) {
                            //alert("found dams record");
                            layerNodes["Development Activities"].records.push(layer.feature);
                        } else {
                            layerNodes[layer.layerName].records.push(layer.feature);
                        }

                    }

                }

            });
            this._writeResults();
        }
        catch (e) {
            console.error(e);
        }
        console.log("complete");
        //alert("identifyCt: " + identifyCt);
        //if (identifyCt <= 0) {
        statusBox._removeStatus("search");
        //}
    },

    _writeJson: function() {
        var layerNodes = this._layerNodes;
        //var output = { results: [{ records: []}] };
        var output = { results: {} };
        var resultCt = 0;
        var layerTrack = "";
        for (idx in layerNodes) {
            //output[idx]["records"] = new Array();
            layerTrack = idx;
            output.results[idx] = { records: [] };
            if (layerNodes[idx].records.length > 0) {
                for (j in layerNodes[idx].records) {
                    output.results[idx].records[j] = layerNodes[idx].records[j].attributes;
                }
                resultCt++;
            }

        }
        //alert(this._layerNodes);
        return dojo.toJson(output);
    },

    _writeResults: function() {
        //this.domNode
        var domNode = this.domNode;
        domNode.innerHTML = "";
        var layerNodes = this._layerNodes;
        //domNode.appendChild(document.createTextNode("this is a test"));
        var layerct = 0;

        var emptyLayers = new Array();

        for (layer in layerNodes) {
            //            if (layerNodes[layer].layerName == "DAMS") {
            //                alert("writing results for: " + layerNodes[layer].layerName + "(" + layerNodes[layer].records.length + ")");
            //            }
            var di = domNode.appendChild(document.createElement("div"));
            di.id = "layer_" + layerct;

            /*
            dojo.connect(di, "onclick", function(evt) {
            //				    alertTxt = "";
            //				    for( evtItm in evt.target.parentNode ){
            //				        alertTxt += evtItm+": "+evt.target.parentNode[evtItm]+"\r";
            //				    }
            //				    alert( alertTxt );
            if( dojo.query('#'+evt.target.parentNode["id"]+' table').style('display') == 'none' ){
            //dojo.removeClass(dojo.query('#'+evt.target.parentNode["id"]+' h3'), "hidden");
            dojo.query('#'+evt.target.parentNode["id"]+' table').style('display','block');
            }else{
            //dojo.addClass(dojo.query('#'+evt.target.parentNode["id"]+' h3'), "hidden");
            dojo.query('#'+evt.target.parentNode["id"]+' table').style('display','none');
            }
    					
			    });
            */

            // Would've liked to do it this way but dojo won't let me
            //var h = di.appendChild(document.createElement("div"));
            //h.appendChild(document.createTextNode(layerNodes[layer].layerName));
            //dojo.addClass(h,"custbtn");
            //dojo.connect(di, "onclick", function(evt){
            //    alert('testing');
            //});

            di.innerHTML += "<h3 onclick=\"resultPanel.toggleLayers(dojo.query('.layerTable',this.parentNode), this);\">" + layerNodes[layer].layerName + "</h3>";
            console.log("***LAYER NAME***: |" + layerNodes[layer].layerName + "|");
            if (layerNodes[layer].layerName == "Property" && layerNodes[layer].records.length > 0) {
                var btn = di.appendChild(document.createElement("div"));

                // Grab the property ids
                var idList = "";
                for (recIdx in layerNodes[layer].records) {
                    idList += layerNodes[layer].records[recIdx].attributes["LDFOID"] + ",";
                }
                addressLabelIds = idList;
                btn.innerHTML = "<div class=\"custbtn\" onclick=\"exportExcel('" + idList + "');\">Export</div>"
                btn.innerHTML = "<div class=\"custbtn\" onclick=\"dijit.byId('dlg_address').show();\" style=\"float:right; margin-right:50px; padding:5px;\">Address Labels</div>"
                //btn.innerHTML += "<div style=\"float:left;\">Address Labels: (<input id=\"addrTypeOwner\" name=\"addrType\" type=\"radio\" value=\"owner\" checked=checked />Owner <input id=\"addrTypePremise\" name=\"addrType\" type=\"radio\" value=\"premise\" />Premise) (<input id=\"addrFileDoc\" name=\"addrFile\" type=\"radio\" value=\"doc\" checked=checked />Word <input id=\"addrFileXls\" name=\"addrFile\" type=\"radio\" value=\"xls\" />Excel)</div><div class=\"custbtn\" onclick=\"exportAddress('" + idList + "');\">Generate</div>"
            } else if (layerNodes[layer].layerName == "Zoning" || layerNodes[layer].layerName == "Zoning (Black & White)") {
                var btn = di.appendChild(document.createElement("div"));
                btn.innerHTML = "<a class=\"resultHeadPdf\" target=\"_blank\" href=\"http://www.pgplanning.org/Assets/Planning/Planning+Resource/Guide+to+Zoning+Categories.pdf\">View Guide</a>";
                btn.innerHTML += "<a class=\"resultHeadLink\" target=\"_blank\" href=\"http://egov.co.pg.md.us/lis/default.asp?File=&Type=TOC\">Zoning Ordinance - Subtitle 27</a>";
            } else if (layerNodes[layer].layerName == "Water Category") {
                var btn = di.appendChild(document.createElement("div"));
                btn.innerHTML = "<a class=\"resultHeadPdf\" target=\"_blank\" href=\"" + documentPath + "/water_and_sewer_cats.pdf\">View Guide</a>";
            } else if (layerNodes[layer].layerName == "Sewer Category") {
                var btn = di.appendChild(document.createElement("div"));
                btn.innerHTML = "<a class=\"resultHeadPdf\" target=\"_blank\" href=\"" + documentPath + "/water_and_sewer_cats.pdf\">View Guide</a>";
            } else if (layerNodes[layer].layerName == "Tree Conservation Plan 1") {
                var btn = di.appendChild(document.createElement("div"));
                btn.innerHTML = "<a class=\"resultHeadPdf\" target=\"_blank\" href=\"http://www.pgplanning.org/Assets/Planning/Environment/Tree+Conservation+Plan+Copy+Request.pdf\">View Request Form</a>";
            } else if (layerNodes[layer].layerName == "Tree Conservation Plan 2") {
                var btn = di.appendChild(document.createElement("div"));
                btn.innerHTML = "<a class=\"resultHeadPdf\" target=\"_blank\" href=\"http://www.pgplanning.org/Assets/Planning/Environment/Tree+Conservation+Plan+Copy+Request.pdf\">View Request Form</a>";
            } else if (layerNodes[layer].layerName == "Green Infrastructure Plan") {
                var btn = di.appendChild(document.createElement("div"));
                btn.innerHTML = "<a class=\"resultHeadPdf\" target=\"_blank\" href=\"" + documentPath + "/GI_Plan.pdf\">View Guide</a>";
            }

            di.innerHTML += "<div style='clear:both;'></div>";
            if (layerNodes[layer].records.length > recordsPerPage) {

                totalPages = Math.floor(layerNodes[layer].records.length / recordsPerPage);
                if (layerNodes[layer].records.length % recordsPerPage > 0) {
                    totalPages++;
                }

                var pageDiv = "<div class='resultpage'>";
                if (layerNodes[layer].recordPage <= 0) {
                    pageDiv += "(prev)";
                } else {
                    pageDiv += "<a href='#' onclick='resultPanel.setPage(\"" + layerNodes[layer].layerName + "\"," + (layerNodes[layer].recordPage - 1) + "); return false;'>(prev)</a>";
                }
                pageDiv += " Page: " + (layerNodes[layer].recordPage + 1 + " of " + totalPages + " ");
                //alert(layerNodes[layer].recordPage + " - " + (layerNodes[layer].records.length / recordsPerPage) + " = " + (layerNodes[layer].recordPage - (layerNodes[layer].records.length / recordsPerPage)));
                if (((layerNodes[layer].recordPage + 1) - (layerNodes[layer].records.length / recordsPerPage)) < 0) {
                    pageDiv += "<a href='#' onclick='resultPanel.setPage(\"" + layerNodes[layer].layerName + "\"," + (layerNodes[layer].recordPage + 1) + "); return false;'>(next)</a>";
                } else {
                    pageDiv += "(next)";
                }
                pageDiv += "</div>";
                di.innerHTML += pageDiv;

            }
            dojo.addClass(di, "resulthead");
            //di.innerHTML += "<div class='loading'>Loading...</div>";
            //if (layerNodes[layer].records.length > 0 && layerNodes[layer].attributes.length > 0 && layerNodes[layer].layerName != "Zoning (Black & White)") {
            if (layerNodes[layer].layerScale != 0 || (layerNodes[layer].records.length > 0 && layerNodes[layer].attributes.length > 0)) {
                di.innerHTML += this.layerTabContent(layerNodes[layer], layer);
            } else {
                dojo.addClass(di, "disabled");
                var notinempty = true;
                for (emptyCk in emptyLayers) {
                    if (emptyLayers[emptyCk] == layerNodes[layer].layerName) {
                        //alert(emptyLayers[emptyCk] + "==" + layerNodes[layer].layerName);
                        notinempty = false;
                        break;
                    }
                }
                if (notinempty) {
                    emptyLayers.push(layerNodes[layer].layerName);
                }
            }
            if (layerNodes[layer].records.length > recordsPerPage) {
                di.innerHTML += pageDiv;
            }
            //dojo.query('.loading',di).style("display", "none");
            layerct++;
        }
        domNode.innerHTML += "<div style='clear:both;'></div>";
        //domNode.innerHTML += "";
        if (emptyLayers.length > 0) {
            var emptyOutput = "<div id='emptylayers' class='resulthead'><h3>The following layers returned no results: </h3><div style='clear:both;'></div>";
            var tmpEmptyOutput = "";
            for (emptyIdx in emptyLayers) {
                if (tmpEmptyOutput != "") {
                    tmpEmptyOutput += ", ";
                }
                tmpEmptyOutput += emptyLayers[emptyIdx];
            }
            emptyOutput += tmpEmptyOutput + "</div>";
            domNode.innerHTML += emptyOutput;
        }
        //alert(emptyOutput);


        //dojo.query('.loading',domNode).style("display", "none");
    },

    showFeature: function(feature) {
        //alert("showing feature: ");
        toggleResultBox(false);
        try {
            showLayer.clear();
            if (feature.geometry.type == "point") {
                //alert(selectLayer.graphics.length);
                var graphic = new esri.Graphic(feature.toJson());
                var identSymbol = new esri.symbol.SimpleMarkerSymbol();
                identSymbol.style = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
                identSymbol.setSize(25);
                identSymbol.setColor(new dojo.Color([0, 255, 255, 0.5]));
                graphic.setSymbol(identSymbol);
                //feature.symbol.setColor(new dojo.Color([0, 255, 255, 0.5]));
                showLayer.add(graphic);
                //alert(selectLayer.graphics.length);
                var newExtent = new esri.geometry.Extent();
                newExtent.xmin = feature.geometry.x - zoomPointEnvelope;
                newExtent.ymin = feature.geometry.y - zoomPointEnvelope;
                newExtent.xmax = feature.geometry.x + zoomPointEnvelope;
                newExtent.ymax = feature.geometry.y + zoomPointEnvelope;
                newExtent.spatialReference = map.spatialReference;
                map.setExtent(newExtent);
            } else {
                var graphic = new esri.Graphic(feature.toJson());
                var identSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 200, 200]), 3), new dojo.Color([0, 200, 200, 0.5]));
                graphic.setSymbol(identSymbol);
                showLayer.add(graphic);
                map.setExtent(graphic.geometry.getExtent().expand(2));
            }
        } catch (err) {
            alert("Error zooming to feature: " + err);
        }

        //}
    },

    showFeatureNoZoom: function(feature) {
        //alert("showing feature, no zoom: ");
        try {
            if (feature.geometry.type == "point") {
                //alert(selectLayer.graphics.length);
                var graphic = new esri.Graphic(feature.toJson());
                var identSymbol = new esri.symbol.SimpleMarkerSymbol();
                identSymbol.style = esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
                identSymbol.setSize(25);
                identSymbol.setColor(new dojo.Color([255, 0, 255, 0.5]));
                graphic.setSymbol(identSymbol);
                //feature.symbol.setColor(new dojo.Color([0, 255, 255, 0.5]));
                platLayer.add(graphic);
                //alert(selectLayer.graphics.length);
                var newExtent = new esri.geometry.Extent();
                newExtent.xmin = feature.geometry.x - zoomPointEnvelope;
                newExtent.ymin = feature.geometry.y - zoomPointEnvelope;
                newExtent.xmax = feature.geometry.x + zoomPointEnvelope;
                newExtent.ymax = feature.geometry.y + zoomPointEnvelope;
                newExtent.spatialReference = map.spatialReference;
                //map.setExtent(newExtent);
            } else {
                var graphic = new esri.Graphic(feature.toJson());
                var identSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 2), new dojo.Color([0, 255, 255, 0.1]));
                graphic.setSymbol(identSymbol);
                platLayer.add(graphic);
                //map.setExtent(graphic.geometry.getExtent().expand(2));
            }
        } catch (err) {
            alert("Error zooming to feature: " + err);
        }

        //}
    },

    showProperty: function(pPropId) {
        //alert("showing, property: " + pPropId);
        var query = new esri.tasks.Query();
        query.returnGeometry = true;
        //query.outFields = [db_name_dams+"."+db_username+"."+arrLayers[arrId][1]+".CASE_NUM"];
        query.where = "PROP_ID=" + pPropId;
        //this.esriMap.setExtent(feature.geometry.getExtent().expand(2));
        var queryTask = new esri.tasks.QueryTask(propertyServiceUrl);
        dojo.connect(queryTask, "onComplete", function(featureSet) {
            if (featureSet.features.length > 0) {
                //alert("property found: "+featureSet.features[0].attributes["PROP_ID"]);
                resultPanel.showFeature(featureSet.features[0]);
                //this.esriMap.setExtent(featureSet.features[0].geometry.getExtent().expand(2));
            }
        });
        queryTask.execute(query);
    },

    showPropertyNoZoom: function(pPropId) {
        //alert("showing, no zoom: " + pPropId);
        var query = new esri.tasks.Query();
        query.returnGeometry = true;
        //query.outFields = [db_name_dams+"."+db_username+"."+arrLayers[arrId][1]+".CASE_NUM"];
        query.where = "PROP_ID=" + pPropId;
        //this.esriMap.setExtent(feature.geometry.getExtent().expand(2));
        var queryTask = new esri.tasks.QueryTask(propertyServiceUrl);
        dojo.connect(queryTask, "onComplete", function(featureSet) {
            if (featureSet.features.length > 0) {
                //alert("property found: "+featureSet.features[0].attributes["PROP_ID"]);
                resultPanel.showFeatureNoZoom(featureSet.features[0]);
                //this.esriMap.setExtent(featureSet.features[0].geometry.getExtent().expand(2));
            }
        });
        queryTask.execute(query);
    },

    showDAMS: function(pPropId, pMapGrid) {

        var query = new esri.tasks.Query();
        var caseFound = false;
        query.returnGeometry = true;
        //query.outFields = [db_name_dams+"."+db_username+"."+arrLayers[arrId][1]+".CASE_NUM"];
        query.where = "CASE_NUM='" + pPropId + "'";
        //this.esriMap.setExtent(feature.geometry.getExtent().expand(2));
        var queryTask;

        resultPanel.damsCt = 0;
        resultPanel.taxMap = pMapGrid;

        for (dsIdx = 0; dsIdx <= 25; dsIdx++) {
            queryTask = new esri.tasks.QueryTask(damsServiceUrl + dsIdx);
            dojo.connect(queryTask, "onComplete", function(featureSet) {
                //alert("features: " + featureSet.error);
                if (featureSet.features != null && featureSet.features.length > 0) {
                    //alert("DAMS record found: " + featureSet.features[0].geometry);
                    resultPanel.showFeature(featureSet.features[0]);
                    //this.esriMap.setExtent(featureSet.features[0].geometry.getExtent().expand(2));
                } else {
                    resultPanel.damsCt++;
                    //alert(resultPanel.damsCt);
                    if (resultPanel.damsCt > 25) {
                        // get tax map grid and reformat to match tax map grid ffield format
                        var tempTMG = resultPanel.taxMap.replace("-", "");
                        tempTMG = tempTMG.replace(" ", "-");
                        if (tempTMG.substring(0, 1) == "0") tempTMG = tempTMG.substring(1, tempTMG.length);

                        alert("This case does not have a valid geography. Zooming to the extent of the tax map grid: " + tempTMG);
                        resultPanel.zoomToTaxMap(tempTMG);
                        //sendToServer(imsQueryURL, WriteEnvelopeQueryTaxMapGrid(tempTMG), 1009);
                    }
                }
            });
            queryTask.execute(query);
        }
    },

    zoomToTaxMap: function(pMapGrid) {
        var query = new esri.tasks.Query();
        query.returnGeometry = true;
        //query.outFields = [db_name_dams+"."+db_username+"."+arrLayers[arrId][1]+".CASE_NUM"];
        query.where = "TAXMAP_GRID='" + pMapGrid + "'";
        //this.esriMap.setExtent(feature.geometry.getExtent().expand(2));
        var queryTask = new esri.tasks.QueryTask(taxmapServiceUrl);
        dojo.connect(queryTask, "onComplete", function(featureSet) {

            var resultFeatures = featureSet.features;
            //alert("features: " + resultFeatures);
            //alert("features[0]: " + resultFeatures[0]);
            //alert("records: " + resultFeatures[0].records);
            resultPanel.showFeature(resultFeatures[0]);
            // Reformat ESRI's inconsistant results to conform with Identify model
            //            dojo.forEach(resultFeatures, function(layer) {
            //                layer["feature"] = layer;
            //                layer["layerName"] = "Tax Grid";
            //                //alert("wssc found: " + layer["feature"].attributes["WSSC_GRID"]);
            //            });

            //            resultPanel._addResults(resultFeatures);
        });
        queryTask.execute(query);
    },

    layerPropertyContent: function(arrProp) {
        var propDetails = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>";
        //	    propDetails += "<td><b>Tax Account:</b></td>";
        //	    propDetails += "<td>"+arrProp["ACCOUNT"]+"</td>";
        //	    propDetails += "</tr>";
        //	    propDetails += "<tr>";
        //http://maps.google.com/maps?saddr=&daddr=002314   TULSON LN,BOWIE, MD 20721-0000
        //	    propDetails += "<td><a href=\"http://maps.google.com/maps?saddr=&daddr="+arrProp["HOUSE_NUMBER"] + " " + arrProp["STREET_NAME"] + " " + arrProp["STREET_TYPE"] + " " + arrProp["CITY"] + ", MD " + arrProp["ZIP5"] + "-" + arrProp["ZIP4"] + "\" target=\"_blank\"><b>Premise Address:</b></a></td>";
        //	    propDetails += "<td>" + arrProp["HOUSE_NUMBER"] + " " + arrProp["STREET_NAME"] + " " + arrProp["STREET_TYPE"]
        //	    propDetails += "<br/>" + arrProp["CITY"] + ", MD " + arrProp["ZIP5"] + "-" + arrProp["ZIP4"] + "</td>";
        //	    propDetails += "</tr>";
        //	    propDetails += "<tr>";
        propDetails += "<td><b>Legal Description:</b></td>";
        propDetails += "<td><i><b>Plat:</b></i> <a href=\"/pgatlas/services/plat.aspx?plat=" + arrProp["PLAT"] + "\" target=\"_blank\">" + arrProp["PLAT"] + "</a>&nbsp;&nbsp;&nbsp;<i><b>Block:</b></i> " + arrProp["BLOCK"] + "&nbsp;&nbsp;&nbsp;<i><b>Lot:</b></i> " + arrProp["LOT"] + "&nbsp;&nbsp;&nbsp;<i><b>Parcel:</b></i> " + arrProp["PARCEL"]
        propDetails += "<br><i><b>Description:</b></i> " + arrProp["PROPERTY_DESC"]
        propDetails += "<br><i><b>Subdivision:</b></i> " + arrProp["SUB_NAME"]
        propDetails += "<br><i><b>Acreage:</b></i> " + arrProp["LAND_AREA_ACRE"]
        propDetails += "<br><i><b>Liber:</b></i> " + arrProp["LIBER"] + "&nbsp;&nbsp;&nbsp;<i><b>Folio:</b></i> " + arrProp["FOLIO"]
        propDetails += "<br><i><b>Tax Map Grid:</b></i> " + arrProp["TAXMAPGRID"] + "&nbsp;&nbsp;&nbsp;<i><b>WSSCGrid:</b></i> " + arrProp["WSSCGRID"]
        propDetails += "<br><i><b>Assessment District:</b></i> " + arrProp["ASSESS_DIST"]
        propDetails += "<br><i><b>Planning Area:</b></i> " + arrProp["PLANAREA"]
        propDetails += "<br><i><b>Planning Analysis Zone:</b></i> " + arrProp["PAZ"] + "</td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Owner Information:</b></td>";
        propDetails += "<td>" + arrProp["OWNER_NAME"] + "<br/>" + arrProp["MAIL_STREET"] + "<br/>" + arrProp["MAIL_CITY"] + ", " + arrProp["MAIL_STATE"] + " " + arrProp["MAIL_ZIP5"] + "-" + arrProp["MAIL_ZIP4"] + "</td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        //http://www.pgatlas.com/pgatlas/Documents/Assessors%20Land%20Use.pdf
        propDetails += "<td><b>Assessor Data:</b></td>";
        propDetails += "<td><i><b>Sales Price:</b></i> " + arrProp["SALES_PRICE"] + "&nbsp;&nbsp;&nbsp;<i><b>Transfer Date:</b></i> " + arrProp["TRANSFER_DATE"]
        propDetails += "<br><i><b>Full Cash Value - Land:</b></i> " + arrProp["FCV_LAND"] + "&nbsp;&nbsp;&nbsp;<i><b>Current Assessment:</b></i> " + arrProp["CURR_ASSESS"]
        propDetails += "<br><i><b>Improvement Cash Value:</b></i> " + arrProp["FCV_IMPS"]
        propDetails += "<br><i><b>Structure (sq/ft):</b></i> " + arrProp["STRUCTURE_SQ_FT"] + "&nbsp;&nbsp;&nbsp;<br/><a href=\"" + documentPath + "/Assessors%20Land%20Use.pdf\" target=\"_blank\"><i><b>Assessor Zone Code:</b></i></a> " + arrProp["AZC"] + "</td>";
        propDetails += "</td>";
        propDetails += "</tr></table>";
        return propDetails;
    },

    layerDAMSContent: function(arrProp) {
        var propDetails = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>";
        //	    propDetails += "<td><b>Title:</b></td>";
        //	    propDetails += "<td>"+arrProp["CASE_TITLE"]+"</td>";
        //	    propDetails += "</tr>";
        //	    propDetails += "<tr>";
        propDetails += "<td><b>Description:</b></td>";
        //propDetails += "<td><b>Case Number:</b> "+arrProp["EVENT_ID"]+" <b>Case Type:</b> "+arrProp["CASE_TYPE"]+" <b>Status:</b> "+arrProp["CASE_STATUS"];
        //propDetails += "<b>Accepted Date:</b> "+arrProp["ACCEPTED_DATE"]+" <b>Status Date:</b> "+arrProp["STATUS_DATE"]+" <b>Validity Date:</b> "+arrProp["VALIDITY_DATE"];
        propDetails += "<td><b>Case Type:</b> " + arrProp["CASE_TYPE"] + " <b>Accepted Date:</b> " + arrProp["ACCEPTED_DATE"] + " <b>Validity Date:</b> " + arrProp["VALIDITY_DATE"];
        propDetails += "<br/><b>Description:</b> " + arrProp["DESCRIPTION"];
        propDetails += "</td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Metrics:</b></td>";
        propDetails += "<td>";
        propDetails += "<b>Acres:</b> " + arrProp["ACRES"] + " <b>Lots:</b> " + arrProp["PRELIMINARY_LOTS"] + " <b>Out Lots:</b> " + arrProp["PRELIMINARY_OUT_LOTS"];
        propDetails += "<b>Parcels:</b> " + arrProp["PRELIMINARY_PARCELS"] + " <b>Out Parcels:</b> " + arrProp["PRELIMINARY_OUT_PARCELS"] + " <b>Gross Floor Area:</b> " + arrProp["GROSS_FLOOR_AREA"];
        propDetails += "<b>Total Units:</b> " + arrProp["TOTAL_UNITS"] + " <b>Units Attached:</b> " + arrProp["UNITS_ATTACHED"] + " <b>Units Detached:</b> " + arrProp["UNITS_DETACHED"];
        propDetails += "<b>Units Multifamily:</b> " + arrProp["UNITS_MULTIFAMILY"];
        propDetails += "</td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Location:</b></td>";
        propDetails += "<td>" + arrProp["LOCATION"] + "</td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Applicant:</b></td>";
        //propDetails += "<td><IFRAME SRC=\"http://www.pgatlas.com/pgatlas/GetApplicantAddress.asp?ApplicantId=" + arrProp["APP_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "<td><IFRAME SRC=\"SA_DAMS.aspx?sType=APPLICANT&sValue=" + arrProp["APP_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Agent:</b></td>";
        //propDetails += "<td><IFRAME SRC=\"http://www.pgatlas.com/pgatlas/GetAgentAddress.asp?AgentId=" + arrProp["AGENT_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "<td><IFRAME SRC=\"SA_DAMS.aspx?sType=AGENT&sValue=" + arrProp["AGENT_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Reviewer:</b></td>";
        propDetails += "<td>" + arrProp["CASE_REVIEWER"] + "</td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Actions:</b></td>";
        //propDetails += "<td><IFRAME SRC=\"http://www.pgatlas.com/pgatlas/GetActions.asp?EventId=" + arrProp["EVENT_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "<td><IFRAME SRC=\"SA_DAMS.aspx?sType=ACTION&sValue=" + arrProp["EVENT_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Zoning:</b></td>";
        //propDetails += "<td><IFRAME SRC=\"http://www.pgatlas.com/pgatlas/GetZoning.asp?EventId=" + arrProp["EVENT_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "<td><IFRAME SRC=\"SA_DAMS.aspx?sType=ZONE&sValue=" + arrProp["EVENT_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Lineage:</b></td>";
        //propDetails += "<td><IFRAME SRC=\"http://www.pgatlas.com/pgatlas/DisplayDamsLineage.htm?caseNumber=" + arrProp["EVENT_ID"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "<td><IFRAME SRC=\"SA_DAMS.aspx?sType=LINEAGE&sValue=" + arrProp["CASE_NUMBER"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "<td><b>Documents:</b></td>";
        //propDetails += "<td><IFRAME SRC=\"http://www.pgatlas.com/mncppc_net/DisplayDamsDocuments.aspx?case_number=" + arrProp["CASE_NUMBER"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "<td><IFRAME SRC=\"SA_DAMS.aspx?sType=DOCUMENT&sValue=" + arrProp["CASE_NUMBER"] + "\" FRAMEBORDER=\"0\"></IFRAME></td>";
        propDetails += "</tr>";
        propDetails += "<tr>";
        propDetails += "</tr></table>";
        return propDetails;
    },

    setPage: function(pLayerId, pPageNum) {

        this._layerNodes[pLayerId].recordPage = pPageNum;
        this._writeResults();
        //alert("layerid: " + pLayerId + " page:" + pPageNum);
        //alert("testing: "+this._layerNodes[pLayerId]);
    },

    toggleLayers: function(pElement, pTarget) {
        //for( idx in pElement.style ){
        //    alert(pElement.style("display"));
        //}
        //alert("name:"+pElement.tagName);
        if (pElement.style("display") != "none") {
            pElement.style("display", "none");
            dojo.addClass(pTarget, "hidden");
        } else {
            pElement.style("display", "block");
            dojo.removeClass(pTarget, "hidden");
        }
    },

    toggleDetails: function(pElement, pTarget) {
        //for( idx in pElement.style ){
        //    alert(pElement.style("display"));
        //}
        //alert("name:"+pElement.tagName);
        if (pElement.style("display") != "none") {
            pElement.style("display", "none");
            //dojo.addClass(pTarget, "hidden");
            pTarget.innerHTML = "(show)";
        } else {
            dojo.isIE ? pElement.style("display", "block") : pElement.style("display", "table-row");
            //pElement.style("display", "table-row");
            //dojo.removeClass(pTarget, "hidden");
            pTarget.innerHTML = "(hide)";
        }
    },

    toggleAllDetails: function(pElement, pTarget) {
        //for( idx in pElement.style ){
        //    alert(pElement.style("display"));
        //}
        //alert("name:"+pElement.tagName);
        //alert(pElement);
        if (pTarget.innerHTML == "Hide All Details") {
            pTarget.innerHTML = "Show All Details";
            dojo.forEach(pElement, function(detailsElement) {
                dojo.style(detailsElement, "display", "none");
            });
        } else {
            pTarget.innerHTML = "Hide All Details";
            dojo.forEach(pElement, function(detailsElement) {
                dojo.isIE ? dojo.style(detailsElement, "display", "block") : dojo.style(detailsElement, "display", "table-row");
            });
        }


        //        if (pElement.style("display") != "none") {
        //            
        //            //dojo.addClass(pTarget, "hidden");
        //            
        //        } else {
        //            
        //            //pElement.style("display", "table-row");
        //            //dojo.removeClass(pTarget, "hidden");
        //            pTarget.innerHTML = "(hide)";
        //        }
    },

    layerTabContent: function(layerResults, pLayer) {
        //alert("called layerTabContent: " + layerResults.records.length);
        //var content = "["+layerName+"]";
        //content += "<i>Total features returned: " + layerResults.features.length + "</i>";
        //content += "<table border='1'><tr><th>TLID</th><th>Owner</th><th>Value</th></tr>";
        var content = "";
        if (layerResults.records.length > 0 && layerResults.attributes.length > 0) {
            content += "<table class=\"layerTable\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
            if (pLayer == "Property") {
                content += "<tr><td colspan=5>";
                content += "<a href=\"#\" onclick=\"resultPanel.toggleAllDetails(dojo.query('.detailsTableProperty'), this);\">Show All Details</a>";
                content += "</td></tr>";
                content += "<tr>";
                content += "<th class=\"maplink\" width=\"50\">Map</th>";
                content += "<th class=\"detlink\" width=\"50\">Details</th>";
                content += "<th>Tax Account</th>";
                content += "<th><a href=\"http://maps.google.com/maps?saddr=&daddr=" + layerResults.records[recIdx].attributes["HOUSE_NUMBER"] + " " + layerResults.records[recIdx].attributes["STREET_NAME"] + " " + layerResults.records[recIdx].attributes["STREET_TYPE"] + " " + layerResults.records[recIdx].attributes["CITY"] + ", MD " + layerResults.records[recIdx].attributes["ZIP5"] + "-" + layerResults.records[recIdx].attributes["ZIP4"] + "\" target=\"_blank\"><b>Premise Address:</b></a></th>";
                content += "<th>Owner Name</th>";
                content += "</tr>";
            } else if (layerResults.records[0].attributes["EVENT_ID"] != undefined) {
                content += "<tr><td colspan=7>";
                content += "<a href=\"#\" onclick=\"resultPanel.toggleAllDetails(dojo.query('.detailsTableDams'), this);\">Show All Details</a>";
                content += "</td></tr>";
                content += "<tr>";
                content += "<th class=\"maplink\" width=\"50\">Map</th>";
                content += "<th class=\"detlink\" width=\"50\">Details</th>";
                content += "<th>Case Number</th>";
                content += "<th>Title</th>";
                content += "<th>Status</th>";
                content += "<th>Status Date</th>";
                content += "<th>Type</th>";
                content += "</tr>";
            } else {
                //alert("writing headers");
                content += "<tr>";
                content += "<th class=\"maplink\">Map</th>";
                // Exceptions for layer specific data
                if (pLayer == "Census Tract 2000") {
                    content += "<th>Census Data</th>";
                    //} else if (pLayer == "Intersection") {
                    //    content += "<th>&nbsp;</th>";
                }
                for (j in layerResults.attributes) {
                    //alert(layerResults.attributes[j]);
                    content += "<th>" + layerResults.attributes[j] + "</th>";
                }
                content += "</tr>";
            }

            //for (recIdx in layerResults.records) {
            //alert("length: " + layerResults.records.length);
            var startIdx = layerResults.recordPage * recordsPerPage;
            var endIdx = startIdx + recordsPerPage;
            if (endIdx > layerResults.records.length) {
                endIdx = layerResults.records.length;
            }
            //alert("start: " + startIdx + " end: " + endIdx);
            for (recIdx = startIdx; recIdx < endIdx; recIdx++) {
                content += "<tbody><tr>";
                if (pLayer == "Property") {
                    content += "<td class=\"maplink\"><a href='#' onclick='resultPanel.showProperty(resultPanel._layerNodes[\"" + pLayer + "\"].records[" + recIdx + "].attributes[\"PROP_ID\"]); return false;'>(show)</a></td>";
                    content += "<td class=\"detlink\"><a href=\"#\" onclick=\"resultPanel.toggleDetails(dojo.query('.detailsTable',this.parentNode.parentNode.parentNode), this);\">(show)</a></td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["ACCOUNT"] + "</td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["HOUSE_NUMBER"] + " " + layerResults.records[recIdx].attributes["STREET_NAME"] + " " + layerResults.records[recIdx].attributes["STREET_TYPE"] + ", " + layerResults.records[recIdx].attributes["CITY"] + ", MD " + layerResults.records[recIdx].attributes["ZIP5"] + "-" + layerResults.records[recIdx].attributes["ZIP4"] + "</td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["OWNER_NAME"] + "</td>";
                    content += "</tr><tr class=\"detailsTable detailsTableProperty\"><td colspan=\"2\" class=\"maplink\">&nbsp;</td><td colspan=\"3\">";
                    content += this.layerPropertyContent(layerResults.records[recIdx].attributes) + "</td>";
                }
                else if (layerResults.records[recIdx].attributes["EVENT_ID"] != undefined) {
                    content += "<td class=\"maplink\"><a href='#' onclick='resultPanel.showDAMS(resultPanel._layerNodes[\"" + pLayer + "\"].records[" + recIdx + "].attributes[\"CASE_NUMBER\"], resultPanel._layerNodes[\"" + pLayer + "\"].records[" + recIdx + "].attributes[\"MAPGRID\"]); return false;'>(show)</a></td>";
                    content += "<td class=\"detlink\"><a href=\"#\" onclick=\"resultPanel.toggleDetails(dojo.query('.detailsTable',this.parentNode.parentNode.parentNode), this);\">(show)</a></td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["CASE_NUMBER"] + "</td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["CASE_TITLE"] + "</td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["CASE_STATUS"] + "</td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["STATUS_DATE"] + "</td>";
                    content += "<td>" + layerResults.records[recIdx].attributes["CASE_TYPE"] + "</td>";
                    content += "</tr><tr class=\"detailsTable detailsTableDams\"><td colspan=\"2\" class=\"maplink\">&nbsp;</td><td colspan=\"5\">";
                    content += this.layerDAMSContent(layerResults.records[recIdx].attributes) + "</td>";
                }
                else {
                    //alert("writing generic content");
                    content += "<td class=\"maplink\"><a href='#' onclick='resultPanel.showFeature(resultPanel._layerNodes[\"" + pLayer + "\"].records[" + recIdx + "]); return false;'>(show)</a></td>";
                    if (pLayer == "Census Tract 2000") {
                        content += "<td><a href=\"SA_Census.aspx?tract_id=" + layerResults.records[recIdx].attributes["Tract"] + "\" target=\"_blank\">View</a></td>";
                        //} else if (pLayer == "Intersection") {
                        //    content += "<td><a href=\"alert('testing');\" target=\"_blank\">Search Property</a></td>";
                    }
                    for (j in layerResults.attributes) {
                        // Exceptions for layer specific data
                        //alert("looping");
                        //alert(layerResults.records[recIdx].attributes[layerResults.attributes[j]]);
                        if ((pLayer == "Historic Sites" && layerResults.attributes[j] == "Description") || (pLayer == "Historic Sites Environmental Settings" && layerResults.attributes[j] == "ID")) {
                            content += "<td><a href=\"historic.aspx?imageID=" + layerResults.records[recIdx].attributes[layerResults.attributes[j]] + "\" target=\"_blank\">" + layerResults.records[recIdx].attributes[layerResults.attributes[j]] + "</a></td>";
                        } else {
                            var tmpVal = layerResults.records[recIdx].attributes[layerResults.attributes[j]];
                            if (tmpVal == null || (isNaN(tmpVal) && dojo.trim(tmpVal) == "")) {
                                tmpVal = "&nbsp;";
                            }
                            content += "<td>" + tmpVal + "</td>";
                        }
                        //alert(content);
                    }
                    //alert(content);
                    //this.showFeature(layerResults.records[recIdx]);
                }
                //alert(content);
                content += "</tr></tbody>";
                //if( pLayer == "DAMS" ){
                //    content += "<tr>";
                //    content += "<td colspan=2>" + this.layerDAMSContent(layerResults.records[recIdx].attributes) + "</td>";
                //    content += "</tr>";
                //}
            }
            /*
            for (var idx = 0, idxl = layerResults.features.length; idx < idxl; idx++) {
            console.log("features " + idx + ": " + layerResults.features[idx].attributes);
            content += "<tr>";
            for (j in layerResults.features[idx].attributes) {
            content += "<td>" + layerResults.features[idx].attributes[j] + "</td>";
            }
            content += "</tr>";
            }
            */
            //content += "</table>";

            //alert(content);
        } else {
            content += "<table class=\"layerTableDisabled\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
            content += "<tr><td>";
            content += "No Data Available At This Scale";
            content += "</td></tr>";
            content += "</table>";
        }
        return content;
    }

});
