﻿


// #########################################################################
//  Search Results:
//
//  Global Variables:
//      currentResultSet
//      currentIndex
//
//  Functions:
//      showParcelSearchResults:
//      goPreviousResults
//      goNextResults
//      printResults
//      onRowMouseOver
//      onRowMouseOut
//      zoomTo
//      zoomToSelected
//      convertFindResult2FeatureSet
//      clearSearchResults
//
// ##########################################################################


var parcelGraphics, bulletGraphics;

var detailGraphic;
var bufferGraphics;
var currentResultSet;
var _currentIndex, _totalRecords, _totalPages;
var _RecsPerPage = 10;
var _isDetailView = true;

var selectID = "PIN";
var resultsRowHighlightColor = "#F5F5F5";
var blank = "<img src=\"Images/blank.gif\" alt=\"\" />";

var parcelHighlightSymbol, parcelSelectedSymbol;

function searchResultsStartup() {

    try {
        parcelGraphics = new esri.layers.GraphicsLayer({ id: "results", displayOnPan: dojo.isIE ? false : true })
        map.addLayer(parcelGraphics);

        bulletGraphics = new esri.layers.GraphicsLayer({ id: "bullets", displayOnPan: dojo.isIE ? false : true })
        map.addLayer(bulletGraphics);

        // Create symbols for result features
        parcelSelectedSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 3);

        parcelHighlightSymbol =
                  new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
                  new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                  new dojo.Color([0, 255, 255]), 3), new dojo.Color([255, 255, 0, 0.50]));




    } catch (Error) {
        console.warn("An error occurred while creating the search results containers:", Error);
    }
}


function showParcelSearchResults(results) {


    try {
        console.debug(results);
        bulletGraphics.clear();
        parcelGraphics.clear();


        currentResultSet = results;
        _currentIndex = 0;
        _totalRecords = results.features.length;

        switch (_totalRecords) {
            case 0:
                // go back
                dojo.style("results-details", { display: "none" });
                dojo.style("results-list", { display: "block" });
                dojo.byId("back").innerHTML = "<a href=\"#\" onmousedown=\"showPanel('" + returnToPanel + "');\">Refine Search Parameters</a>";
                dojo.byId("grid").innerHTML = "<p>Sorry, but your query return no results from the database</p><p>The query Attempted was: <br/>" + txtWhereClause + "</p>";
                showPanel("results");
                return false;
                break;
            case 1:
                //console.debug("cursor: " + i);
                var graphic = results.features[0];
                graphic.setSymbol(parcelSelectedSymbol);
                parcelGraphics.add(graphic);
                parcelGraphics.show();
                showDetails(0);
                break;
            default:
                _initPagerSettings(results);
                printResults();
                break;
        }
    } catch (Error) {
        showError("An Error occurred while processing your result set:", Error);
    }

}
function goFirstPage() {

    _currentIndex = 0;
    printResults();

}

function goPreviousResults() {
    _currentIndex = _currentIndex - 1
    printResults();
}

function goNextResults() {
    _currentIndex = _currentIndex + 1;
    printResults();
}

function goLastPage() {
    _currentIndex = _totalPages - 1;
    printResults();
}

function searchResults_show(mode) {

    if (mode == "list") {
        dojo.style("results-details", { display: "none" });
        dojo.style("results-list", { display: "block" });
    } else {
        dojo.style("results-details", { display: "block" });
        dojo.style("results-list", { display: "none" });

        if (parcelGraphics.graphics.length > 1) {
            dojo.byId("results-details-header").innerHTML = "<div><a href=\"#\" onmousedown=\"goBacktoResults();\">Back to Search Results</a></div>";
        } else {
            dojo.byId("results-details-header").innerHTML = "<div class=\"captionbr\">Search Results</div>";
        }
    }
    showPanel("results");
}

function _initPagerSettings(results) {

    // figure the paging info
    _totalRecords = results.features.length;
    _totalPages = Math.floor(_totalRecords / _RecsPerPage);
    if (_totalRecords % _RecsPerPage > 0)
        _totalPages++

}

function printResults() {



    // set results to current result set
    var results = currentResultSet;

    // calculate the page info
    var currentPage = _currentIndex + 1;
    var startIndex = _currentIndex * _RecsPerPage;
    var endIndex = (_currentIndex + 1) * _RecsPerPage;
    if (results.features.length < endIndex)
        endIndex = results.features.length;


    parcelGraphics.clear();
    bulletGraphics.clear();
    parcelGraphics.show();
    bulletGraphics.show();

    var s = [];
    s.push(_resultsHeader(currentPage));
    s.push(_resultsToolbar());

    if (!_isDetailView) {
        s.push("<div class=\"gray\"><table cellspacing=\"2\" cellpadding=\"2\" width=\"100%\" border=\"1\"><tbody>");
        s.push(ParcelRowHeader());
    } else {
        s.push("<div class=\"gray\"><table cellspacing=\"2\" cellpadding=\"2\" width=\"100%\" border=\"0\"><tbody>");
    }


    //console.debug("inside");
    // Add result features to map and table
    var j = 0;
    for (var i = startIndex, il = endIndex; i < il; i++) {
        var graphic = results.features[i];

        // Create template for the info window
        var parcels_content = parcelBrief(graphic, j);
        infoTemplate = new esri.InfoTemplate(parcels_title_content, parcels_content);

        //Add result feature to map
        graphic.setSymbol(parcelSelectedSymbol);
        graphic.setInfoTemplate(infoTemplate);
        parcelGraphics.add(graphic);

        // get center
        var fExtent = graphic.geometry.getExtent();
        var centerPt = new esri.geometry.Point;
        centerPt = fExtent.getCenter();

        // add the point to the map
        var bNum = j + 1
        var bulletURL = "images/Bullets/bullet_" + bNum + ".png"
        var mSym = new esri.symbol.PictureMarkerSymbol(bulletURL, 12, 12);
        var gPt = new esri.Graphic(centerPt, mSym, graphic.attributes, infoTemplate);
        bulletGraphics.add(gPt);

        //isDetailView = true;

        // Get the CSS Class for the row...
        var cssClass = "r1";
        if (i % 2 == 0)
            cssClass = "r2";

        //s.push("<tr onmouseover=\"onRowMouseOver(" + i + ");\" onmouseout=\"onRowMouseOut(" + i + ");\" class=\"" + cssClass + "\" ><td valign=\"top\"><div onclick=\"zoomTo(" + i + ");\"><img src=\"images/zoomtofeature.gif\" alt=\"zoomto\" /></div></td><td>" + owner1 + "<br/>" + owner2 + "</td><td>" + pin + "</td><td>" + street + "</td></tr>");
        var rowText = "";
        if (_isDetailView) {

            rowText = "<tr onmouseover=\"onRowMouseOver(this, " + j + ");\" onmouseout=\"onRowMouseOut(this, " + j + ");\" class=\"" + cssClass + "\" style=\"border:none 1px red;\" >";
            rowText += "<td valign=\"top\" align=\"center\"><img src=\"" + bulletURL + "\" /><div onclick=\"zoomTo(" + j + ");\"><img src=\"images/zoomtofeature.gif\" alt=\"zoomto\" /></div></td>";
            rowContent = graphic.getContent();
            rowText += "<td><div>" + rowContent + "</td></tr>";


        } else {
            rowText = ParcelRow(graphic, j, cssClass);
        }
        s.push(rowText);

        j++
    } // end for


    s.push("</tbody></table></div>");


    if (_totalPages > 1) {
        _resultsFooter(currentPage, _totalPages);
    }
    else {
        // hide the footer
        dojo.style("pager", { display: "none" });
    }



    // if we have buffer graphics then add them to the map
    if (bufferGraphics != null) {
        dojo.forEach(bufferGraphics, function(g) {
            var outlineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 1);
            g.setSymbol(outlineSymbol);
            map.graphics.add(g);
        });
    }

    s.push("</tbody></table>");

    dojo.byId("grid").innerHTML = s.join("");
    map.graphics.enableMouseEvents();
    searchResults_show("list");
}


function _resultsHeader(currentPage) {
    var s = [];
    s.push("<table width=\95%\"><tbody><tr><td class=\"captionbr\">Search Results</td><td align=\"right\">");
    s.push("<a href=\"#\" onmousedown=\"_isDetailView=true;printResults();\" ><img src=\"images/details.png\"/></a>&nbsp;");
    s.push("<a href=\"#\" onmousedown=\"_isDetailView=false;printResults();\" ><img src=\"images/list.png\"/></a>");
    s.push("</td<tr></tbody></table>");
    s.push("<div>" + _totalRecords + " Features Found." + blank + "(page " + currentPage + " of " + _totalPages + ")</div>");
    return s.join("");
}

function _resultsToolbar() {
    var s = [];
    s.push("<table width=\95%\"><tbody><tr><td width=\"50%\" align=\"left\">");
    s.push("<div style=\"font-size:small\"><div><a href=\"javascript:zoomToSelected();\">zoom to all</a></div>");
    s.push("<div><a href=\"javascript:clearAllGraphics();\">Clear all</a></div></div>");
    s.push("</td><td>");
    s.push("<div><a href=\"javascript:exportExcel();\">Export to Excel</a></div>");
    //s.push("<div><a href=\"javascript:showGrid();\">Show as Table</a></div>");
    s.push("</td></tr>");
    s.push("</tbody></table>");
    s.push("<hr/>");
    return s.join("");
}


function _resultsFooter(currentPage, totalPages) {

    try {

        // print the paging information at bottom...
        var prevTag, nextTag;
        var footer = "";

        if (currentPage > 1)
            prevTag = "<a href=\"javascript:goPreviousResults();\"><img onmouseover=\"this.src='images/previous.gif'\" onmouseout=\"this.src='images/previous.gif'\" src=\"images/previous.gif\" alt='Previous'/> previous</a>&nbsp;&nbsp;";
        else
            prevTag = blank;

        if (currentPage < totalPages)
            nextTag = "<a style=\"position:absolute;right:2px;\" href=\"#\" onmousedown=\"javascript:goNextResults();\">next <img onmouseover=\"this.src='images/next.gif'\" onmouseout=\"this.src='images/next.gif'\" src=\"images/next.gif\" alt='Next'/></a>";
        else
            nextTag = blank;
        footer = prevTag + nextTag;
        dojo.byId("pager").innerHTML = footer;

        // show the footer
        dojo.style("pager", { display: "block" });
    } catch (Error) {
        console.warn("An Error occurred creating the footer...", Error);
        dojo.style("pager", { display: "none" });
    }

}



// Functions to handle common result display...
function convertFindResult2FeatureSet(results) {
    var features = [];
    for (var i = 0; i < results.length; i++) {
        //console.debug(results[i].layerName);
        features.push(results[i].feature);
        //console.debug(i);
    }
    var featureSet = new esri.tasks.FeatureSet();
    featureSet.features = features;
    //console.debug(features.length + " features in the array");
    //console.debug(featureSet.features.length + " features in the dataset");
    showParcelSearchResults(featureSet);
}

// Highlight the feature when the mouse hovers over the corresponding grid row
function onRowMouseOver(r, index) {
    try {
        var selectedGraphic = parcelGraphics.graphics[index];
        if (selectedGraphic != null) {
            selectedGraphic.setSymbol(parcelHighlightSymbol);
            selectedGraphic.show();
        }
        return
    } catch (Err) {
        console.debug("Error:" + Err);
    }
}

// Remove feature highlight when mouse goes off the corresponding grid row
function onRowMouseOut(r, index) {
    try {
        var selectedGraphic = parcelGraphics.graphics[index];
        if (selectedGraphic != null) {
            selectedGraphic.setSymbol(parcelSelectedSymbol);
        }
        return
    } catch (Err) {
        console.debug("Error:" + Err);
    }
}

function showDetails(index) {

    // zoom to the graphic and highlight
    try {
        graphic = parcelGraphics.graphics[index];
        if (graphic != null) {

            detailGraphic = new esri.Graphic(graphic.toJson());

            console.debug(graphic);
            console.debug(detailGraphic);
            var parcels_content = parcelDetails(detailGraphic);
            infoTemplate = new esri.InfoTemplate(parcels_title_content, parcels_content);

            //Add result feature to map
            console.debug("resetting the info template");
            //graphic.setSymbol(parcelHighlightSymbol);
            detailGraphic.setInfoTemplate(infoTemplate);

            // this is a work around for problem with dojo shape is null when shape is not in the current extent
            //  problem occurred at v1.4
            zoomAfterLoadEvntHandle = dojo.connect(map, "onExtentChange", function() {
                try {
                    detailGraphic.setSymbol(parcelHighlightSymbol);
                } catch (Error) {
                    console.debug("Still getting the error...Try Again?");
                }
                dojo.disconnect(zoomAfterLoadEvntHandle);
            });
            

            console.debug("evaluating");
            dojo.byId("results-details-content").innerHTML = detailGraphic.getContent();
            map.infoWindow.hide();

            // Create template for the info window
            console.debug("zooming");
            zoomMap(detailGraphic.geometry.getExtent().expand(1.3));
            searchResults_show("details");
        }
    }

    catch (Err) {

        //alert("error: " + Err.message);
        console.debug(Err)
    }
}

function goBacktoResults() {

    try {
        // reselect the parcels
        printResults();

    } catch (Error) {
        console.debug("Error in 'goBacktoResults' function");
        console.debug(Error);
    }

}

function clearSearchResultsPanel() {

    try {

        // reset the global variables
        detailGraphic = null;
        parcelGraphics.clear();
        bulletGraphics.clear();
        parcelGraphics.hide();
        bulletGraphics.hide();
        currentResultSet = null;
        bufferGraphics = null;
        additionalFields = [];

        // reset the large grid
        //dojo.style("resultsetbutton", { display: "none" });



        // clear the node
        dojo.byId("grid").innerHTML = "";
        dojo.byId("pager").innerHTML = "";
    } catch (Error) {
        console.warn("Error in the function 'clearSearchResults': ", Error);

    }

}


function zoomTo(index, show) {

    try {
        console.debug("Zoom to: " + index);
        var selectedGraphic = parcelGraphics.graphics[index];


        if (selectedGraphic != null) {
            zoomMap(selectedGraphic.geometry.getExtent().expand(1.3));

            if (show) {
                // calculate the height/width
                var windowWidth = 250;
                var windowHeight = 300;

                if (map.height < 300) {
                    showPanel("details-sidebar");
                    dojo.byId("details-sidebar-content").innerHTML = selectedGraphic.getContent();
                    dojo.byId("details-sidebar-header").innerHTML = selectedGraphic.getTitle();
                }
                else {
                    var windowHeight = goodHeight;
                    var dHeight = (map.height / 2) - 50;


                    if (windowHeight > dHeight)
                        windowHeight = dHeight;

                }

                zoomAfterLoadEvntHandle = dojo.connect(map, "onExtentChange", showInfoWindowAfterZoom);
                map.infoWindow.setContent(selectedGraphic.getContent());
                map.infoWindow.setTitle(selectedGraphic.getTitle());
                map.infoWindow.resize(windowWidth, windowHeight);
            } else { map.infoWindow.hide(); }
        }
    }
    catch (Err) {
        console.debug(Err)
    }
}

function zoomToResultbyIndex(indx) {
    if (currentResultSet != null) {
        var graphic = currentResultSet.features[indx];
        if (graphic != null) {
            try {
                var parcels_content = getParcelContent(graphic);
                infoTemplate = new esri.InfoTemplate(parcels_title_content, parcels_content);

                //Add result feature to map
                graphic.setSymbol(parcelHighlightSym);
                graphic.setInfoTemplate(infoTemplate);
                map.graphics.clear();
                map.graphics.add(graphic);

                zoomGraphic(graphic, true);
                dijit.byId("TaxCardReport").hide();
                dojo.style("resultsetbutton", { display: "block" });
            } catch (Err) {
                console.debug(Err)
            }
        } // if graphic is not null
    } // if current results set is not null
} // end function

function zoomToSelected() {

    try {
        var fullExt = esri.graphicsExtent(currentResultSet.features);
        if (fullExt != null)
            map.setExtent(fullExt.expand(1.1));
    } catch (Error) {
        console.warn("An Error occurred in the application in routine 'zoomToSelected'", Error);
    }

}


function zoomGraphic(selectedGraphic, show) {
    if (selectedGraphic != null) {
        zoomMap(selectedGraphic.geometry.getExtent().expand(1.3));

        if (show) {
            // calculate the height/width
            var windowWidth = 250;
            var windowHeight = 300;
            if (map.height < 300) {
                showPanel("details-sidebar");
                dojo.byId("details-sidebar-content").innerHTML = selectedGraphic.getContent();
                dojo.byId("details-sidebar-header").innerHTML = selectedGraphic.getTitle();
            }
            else {
                var windowHeight = goodHeight;
                var dHeight = (map.height / 2) - 50;
                if (windowHeight > dHeight)
                    windowHeight = dHeight;
            }

            zoomAfterLoadEvntHandle = dojo.connect(map, "onExtentChange", showInfoWindowAfterZoom);
            map.infoWindow.setContent(selectedGraphic.getContent());
            map.infoWindow.setTitle(selectedGraphic.getTitle());
            map.infoWindow.resize(windowWidth, windowHeight);
        }
    }

}

var zoomAfterLoadEvntHandle;
function showInfoWindowAfterZoom() {
    // show the info window
    try {
        var pt = map.extent.getCenter();
        var spt = map.toScreen(pt)
        if (spt != null) {
            map.infoWindow.show(spt, map.getInfoWindowAnchor(spt));
        }
    }
    catch (Err) { console.debug(Err); }
    dojo.disconnect(zoomAfterLoadEvntHandle);
}


function addToSelectedGraphics(results) {



    try {
        console.debug(currentResultSet);

        var features = [];

        if (currentResultSet != null) {
            features = currentResultSet.features;

        } else {
            currentResultSet = new esri.tasks.FeatureSet();
            _currentIndex = 0;
        }

        var prevSelected = [];
        dojo.forEach(features, function(graphic) {
            var id = graphic.attributes[selectID]
            prevSelected.push(id);
        });

        console.debug(prevSelected);


        dojo.forEach(results.features, function(graphic) {
            var id = graphic.attributes[selectID];
            if (dojo.indexOf(prevSelected, id) < 0) {
                features.push(graphic);
            }
        });

        currentResultSet.features = features;
        _totalRecords = currentResultSet.features.length;

        //
        _initPagerSettings(currentResultSet);
        goLastPage();
    } catch (Error) { console.warn("error occurred in AddToSelectedGraphic:", Error); }


}


function exportExcel() {

    //Create items array to be added to stores data
    var items = []; //all items to be stored in data store
    for (var i = 0, il = currentResultSet.features.length; i < il; i++) {
        items.push(currentResultSet.features[i].attributes); //append each attribute list as item in store
    }

    //Create data object to be used in store
    var data = {
        items: items
    };

    var iframeDocument = dojo.isIE ? printingHiddenFrame.contentWindow.document : printingHiddenFrame.contentDocument;
    iframeDocument.getElementById("exportData").value = dojo.toJson(data);
    iframeDocument.getElementById("export").submit();

}

////////function exportExcel() {


////////    try {

////////        var results = currentResultSet.features;
////////        var items = []; //all items to be stored in data store
////////        dojo.forEach(results, function(feature, index) {
////////            items.push(feature.attributes);  //append each attribute list as item in store
////////        });

////////        //create data object to be used in store
////////        var data = {
////////            identifier: "NCPIN",
////////            items: items
////////        };

////////        console.debug("finished creating the data store");

////////        //esri.config.defaults.io.proxyUrl = "proxy.ashx";
////////        //esri.config.defaults.io.alwaysUseProxy = false;
////////        esri.request({
////////            url: dataHandlerURL,
////////            postData: dojo.toJson(data),
////////            handleAs: "json",
////////            callbackParamName: "callback",
////////            load: function(response, io) {

////////                if (dojo.isIE) {

////////                    showTaskResults("Your Download is Ready <br/><br/> <a href=\"" + response.href + "\" target=\"blank\">Click here to download</a>");

////////                } else {
////////                    searchWin = window.open(response.href, "ExportFile");
////////                    if (searchWin.opener == null)
////////                        searchWin.opener = self;
////////                }
////////            },
////////            error: function(error) {
////////                alert(error.message);
////////            }
////////        }, true);

////////        //["CYPAR", "OWNER", "ADDRESS", "DEED_ACRES", "TOTAL_ACRES", "PIN", "BOOK_PAGE", "DEED_YEAR", "SITUS_ADDX", "TAX_VALUE", "SALE_DATE", "SALE_PRICE", "REMARKS", "TC", "ACCOUNT", "HT_SQ_FEET", "LAND_USE_DESC", "YEAR_BUILT", "EFF_YR_BLT", "NOTES", "FIRE_DIST"];

////////        //var items = getParcelDataStore(currentResultSet.features);
//////////        var items = [];
//////////        dojo.forEach(currentResultSet.features, function(f, indx) {

//////////            var item = { id: indx,
//////////                cypar: getFieldValue(f, "CYPAR"),
//////////                owner: getFieldValue(f, "OWNER"),
//////////                address: getFieldValue(f, "ADDRESS"),
//////////                deed_acres: getFieldValue(f, "DEED_ACRES"),
//////////                total_acres: getFieldValue(f, "TOTAL_ACRES")           
//////////            }
//////////            items.push(item);
//////////          
//////////        });
////////        
////////        
////////        

//////////        //Create data object to be used in store
//////////        var data = {
//////////            identifier: "id", //This field needs to have unique values
//////////            items: items
//////////        };

//////////        var iframeDocument = dojo.isIE ? printingHiddenFrame.contentWindow.document : printingHiddenFrame.contentDocument;
//////////        iframeDocument.getElementById("data").value = dojo.toJson(data);
//////////        iframeDocument.getElementById("results").submit();



////////    } catch (error) {

////////        var yy = [];
////////        console.debug(error);
////////        yy.push("An Error Occured in the Application...");
////////        yy.push("<div>" + error.message + "</div>");
////////        dojo.forEach(error.details, function(detail) {
////////            yy.push("<div>" + detail + "</div>");
////////        });

////////        dojo.byId("info").innerHTML = yy.join("");
////////        showPanel("info");


////////    }

////////}

function showGrid(results) {
    map.graphics.clear();
    var dataforGrid = [];

    var results = currentResultSet.features;
    var items = []; //all items to be stored in data store
    dojo.forEach(results, function(feature, i) {

        var graphic = feature;
        var attValues = [];
        attValues.push(i);
        console.debug(graphic.attributes);
        var featureAttributes = graphic.attributes;
        for (att in featureAttributes) {
            if (dojo.indexOf(parcels_table_fields, att) > -1) {
                attValues.push(featureAttributes[att]);
            }
        }

        dataforGrid.push(attValues); //push attributes into the array, one row at a time


    });

    var h = map.height;
    var w = map.width + 260;
    dojo.style('gridNode', { height: h + "px" });

    var model = new dojox.grid.data.Table(null, dataforGrid);

    var layout = [gridview1];
    gridWidget.setModel(model);
    gridWidget.setStructure(layout);
    dijit.byId("TaxCardReport").show();
}


// #################################################################################
//  Show Google Street View
function showGoogleStreetViewByIndex(indx) {
    var graphic = currentResultSet.features[indx];
    if (graphic != null) {
        showGoogleStreetView(graphic);
    }
}
function showGoogleStreetView(graphic) {
    try {
        console.debug(graphic);
        var pt = graphic.geometry.getExtent().getCenter();
        var ptGraphic = new esri.Graphic(pt);
        gsvc = new esri.tasks.GeometryService(geoServiceUrl);
        // out spatial reference is WGS-84
        var outSR = new esri.SpatialReference({ wkid: 4326 });
        gsvc.project([ptGraphic], outSR, function(features) {
            pt = features[0].geometry;
            var url = "http://maps.google.com/maps?ll=${latt},${long}&spn=0,359.159546&z=11&layer=c&cbll=${latt},${long}&cbp=12,0,,0,5";
            url = esri.substitute({ latt: pt.y, long: pt.x }, url);
            window.open(url);
        });
    } catch (Error) {
        console.debug(Error);
    }
}






















































//////// #########################################################################
////////  Search Results:
////////
////////  Global Variables:
////////      currentResultSet
////////      currentIndex
////////
////////  Functions:
////////      showParcelSearchResults:
////////      goPreviousResults
////////      goNextResults
////////      printResults
////////      onRowMouseOver
////////      onRowMouseOut
////////      zoomTo
////////      zoomToSelected
////////      convertFindResult2FeatureSet
////////      clearSearchResults
////////
//////// ##########################################################################


//////var parcelGraphics;
//////var currentIndex;
//////var RecsPerPage = 10;
//////var isDetailView = true;
//////var detailGraphic;
//////var bufferGraphics;
//////var currentResultSet, currentIndex;
//////var additionalFields = [];
//////var resultsPanelMode = "list"  // list | detail



//////var resultsRowHighlightColor = "#F5F5F5";

//////var blank = "<img src=\"Images/blank.gif\" alt=\"\" />";

//////function showParcelSearchResults(results) {
//////    //console.debug("Length of features set: " + results.features.length);
//////    currentResultSet = results;
//////    currentIndex = 0;
//////    if (results.features.length == 0) {

//////        // go back
//////        dojo.byId("back").innerHTML = "<a href=\"#\" onmousedown=\"showPanel('" + returnToPanel + "');\">Refine Search Parameters</a>";
//////        dojo.byId("grid").innerHTML = "<p>Sorry, but your query return no results from the database</p><p>The query Attempted was: <br/>" + txtWhereClause + "</p>";
//////        searchResults_show("list");
//////        return false;
//////    }
////////    maxPage = 1
////////    if (results.features.length <= RecsPerPage)
////////        maxPage = 1;
////////    else {

////////        if ((results.length % RecsPerPage) == 0)
////////            maxPage = Math.round((results.features.length / RecsPerPage));
////////        else
////////            maxPage = Math.round((results.features.length / RecsPerPage)) + 1;
////////    }

//////    if (results.features.length == 1) {
//////        map.graphics.clear();
//////        parcelGraphics = [];
//////        //console.debug("cursor: " + i);
//////        var graphic = results.features[0];
//////        var parcels_content = getParcelContent(graphic);
//////        infoTemplate = new esri.InfoTemplate(parcels_title_content, parcels_content);

//////        //Add result feature to map
//////        graphic.setSymbol(parcelHighlightSym);
//////        graphic.setInfoTemplate(infoTemplate);
//////        
//////        dojo.byId("results-details-content").innerHTML = graphic.getContent(); ;
//////        detailGraphic = graphic;
//////        searchResults_show("details");

//////        // Create template for the info window
//////        map.graphics.add(graphic);
//////        zoomMap(graphic.geometry.getExtent().expand(1.3));
//////    } else {
//////        printResults();
//////    }
//////}
//////function goPreviousResults() {
//////    currentIndex = currentIndex - 1
//////    printResults();
//////}

//////function goNextResults() {
//////    currentIndex = currentIndex + 1;
//////    printResults();
//////}

//////function searchResults_show(mode) {

//////    if (mode == "list") {
//////        dojo.style("results-details", { display: "none" });
//////        dojo.style("results-list", { display: "block" });
//////    } else {
//////        dojo.style("results-details", { display: "block" });
//////        dojo.style("results-list", { display: "none" });

//////        if (parcelGraphics.length > 1) {
//////            dojo.byId("results-details-header").innerHTML = "<div><a href=\"#\" onmousedown=\"goBacktoResults();\">Back to Search Results</a></div>";
//////        } else {
//////            dojo.byId("results-details-header").innerHTML = "<div class=\"captionbr\">Search Results</div>";
//////        }
//////    }
//////    showPanel("results");        
//////}

//////function printResults() {
//////    map.graphics.clear();
//////    var results = currentResultSet;
//////    
//////    var totalRec = results.features.length;
//////    var totalPages = Math.floor(totalRec / RecsPerPage);
//////    if (totalRec % RecsPerPage > 0)
//////        totalPages++
//////    var currentPage = currentIndex + 1;


//////    var startIndex = currentIndex * RecsPerPage;
//////    var endIndex = (currentIndex + 1) * RecsPerPage;
//////    if (results.features.length < endIndex)
//////        endIndex = results.features.length;

//////    // Create symbols for result features
//////    var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
//////                  new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
//////                  new dojo.Color([161, 218, 215]), 3), new dojo.Color([20, 150, 235, 0.50]));


//////    var s = [];

//////    parcelGraphics = [];

//////    s.push("<table width=\95%\"><tbody><tr><td class=\"captionbr\">Search Results</td><td align=\"right\">");
//////    s.push("<a href=\"#\" onmousedown=\"isDetailView=true;printResults();\" ><img src=\"images/details.png\"/></a>&nbsp;");
//////    s.push("<a href=\"#\" onmousedown=\"isDetailView=false;printResults();\" ><img src=\"images/list.png\"/></a>");
//////    s.push("</td<tr></tbody></table>");


//////    s.push("<div>" + this.currentResultSet.features.length + " Features Found." + blank + "(page " + currentPage + " of " + totalPages + ")</div>");
//////    s.push("<table width=\95%\"><tbody><tr><td width=\"50%\" align=\"left\">");
//////    
//////    s.push("<div style=\"font-size:small\"><div><a href=\"javascript:zoomToFullExtentOfFeatureGroup(parcelGraphics);\">zoom to all</a></div>");
//////    s.push("<div><a href=\"javascript:clearAllGraphics();\">Clear all</a></div></div>");

//////    s.push("</td><td>");
//////    s.push("<div><a href=\"javascript:exportExcel();\">Export to Excel</a></div>");

//////    s.push("<div><a href=\"javascript:showGrid();\">Show as Table</a></div>");
//////    s.push("</td></tr>");

//////    s.push("</tbody></table>");
//////    s.push("<hr/>");

//////    s.push("<div class=\"gray\"><table cellspacing=\"2\" cellpadding=\"2\"><tbody>");


//////    //console.debug("inside");
//////    // Add result features to map and table
//////    var j = 0;
//////    for (var i = startIndex, il = endIndex; i < il; i++) {
//////        //console.debug("cursor: " + i);
//////        var curFeature = results.features[i];
//////        var graphic = curFeature;

//////        // Create template for the info window
//////        var parcels_content = getParcelContent(graphic, i);
//////        infoTemplate = new esri.InfoTemplate(parcels_title_content, parcels_content);

//////        //Add result feature to map
//////        graphic.setSymbol(parcelHighlightSym);
//////        graphic.setInfoTemplate(infoTemplate);
//////        map.graphics.add(graphic);

//////       
//////        // get center
//////        var fExtent = graphic.geometry.getExtent();
//////        var centerPt = new esri.geometry.Point;
//////        centerPt = fExtent.getCenter();

//////        // add the point to the map
//////        var bNum = j + 1
//////        var bulletURL = "images/Bullets/bullet_" + bNum + ".png"
//////        var mSym = new esri.symbol.PictureMarkerSymbol(bulletURL, 12, 12);
//////        var gPt = new esri.Graphic(centerPt, mSym, null, null);
//////        map.graphics.add(gPt);

//////        //isDetailView = true;

//////        // Get the CSS Class for the row...
//////        var cssClass = "r1";
//////        if (i % 2 == 0)
//////            cssClass = "r2";

//////        //s.push("<tr onmouseover=\"onRowMouseOver(" + i + ");\" onmouseout=\"onRowMouseOut(" + i + ");\" class=\"" + cssClass + "\" ><td valign=\"top\"><div onclick=\"zoomTo(" + i + ");\"><img src=\"images/zoomtofeature.gif\" alt=\"zoomto\" /></div></td><td>" + owner1 + "<br/>" + owner2 + "</td><td>" + pin + "</td><td>" + street + "</td></tr>");
//////        var rowText = "";
//////        if (isDetailView) {

//////            rowText = "<tr onmouseover=\"onRowMouseOver(this, " + j + ");\" onmouseout=\"onRowMouseOut(this, " + j + ");\" class=\"" + cssClass + "\" style=\"border:none 1px red;\" >";
//////            rowText += "<td valign=\"top\" align=\"center\"><img src=\"" + bulletURL + "\" /><div onclick=\"zoomTo(" + j + ");\"><img src=\"images/zoomtofeature.gif\" alt=\"zoomto\" /></div></td>";
//////            rowContent = graphic.getContent();
//////            rowText += "<td><div>" + rowContent + "</td></tr>";

//////        } else {

//////            rowText = ParcelRow(graphic, j, cssClass);

//////            
//////        }
//////        s.push(rowText);

//////        parcelGraphics.push(graphic);

//////        j++
//////    } // end for


//////    s.push("</tbody></table></div>");




//////    if (totalPages > 1) {

//////        // print the paging information at bottom...
//////        var prevTag, nextTag;
//////        var footer = "";

//////        if (currentPage > 1)
//////            prevTag = "<a href=\"javascript:goPreviousResults();\"><img onmouseover=\"this.src='images/b_previous_over.gif'\" onmouseout=\"this.src='images/b_previous.gif'\" src=\"images/b_previous.gif\" alt='Previous'/></a>&nbsp;&nbsp;";
//////        else
//////            prevTag = blank;

//////        if (currentPage < totalPages)
//////            nextTag = "<a style=\"position:absolute;right:2px;\" href=\"#\" onmousedown=\"javascript:goNextResults();\"><img onmouseover=\"this.src='images/b_next_over.gif'\" onmouseout=\"this.src='images/b_next.gif'\" src=\"images/b_next.gif\" alt='Next'/></a>";
//////        else
//////            nextTag = blank;
//////        footer = prevTag + nextTag;

//////        dojo.byId("pager").innerHTML = footer;

//////        // show the footer
//////        dojo.style("pager", { display: "block" });

//////    }
//////    else {
//////        // hide the footer
//////        dojo.style("pager", { display: "none" });
//////    }



//////    // if we have buffer graphics then add them to the map
//////    if (bufferGraphics != null) {
//////        dojo.forEach(bufferGraphics, function(g) {
//////            var outlineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 1);
//////            g.setSymbol(outlineSymbol);
//////            map.graphics.add(g);
//////        });
//////    }

//////    s.push("</tbody></table>");

//////    dojo.byId("grid").innerHTML = s.join("");
//////    map.graphics.enableMouseEvents();
//////    searchResults_show("list");
//////}

//////// Functions to handle common result display...
//////function convertFindResult2FeatureSet(results) {
//////    var features = [];
//////    for (var i = 0; i < results.length; i++) {
//////        console.debug(results[i].layerName);
//////        features.push(results[i].feature);
//////        console.debug(i);
//////    }
//////    var featureSet = new esri.tasks.FeatureSet();
//////    featureSet.features = features;
//////    console.debug(features.length + " features in the array");
//////    console.debug(featureSet.features.length + " features in the dataset");
//////    showParcelSearchResults(featureSet);
//////}

//////// Highlight the feature when the mouse hovers over the corresponding grid row
//////function onRowMouseOver(r, index) {

//////    try {
//////        //var selectedGraphic = map.graphics.graphics[index];
//////        var selectedGraphic = parcelGraphics[index];
//////        if (selectedGraphic != null) {
//////            var highlightSymbol =
//////                  new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
//////                  new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
//////                  new dojo.Color([0, 255, 255]), 3), new dojo.Color([255, 255, 0, 0.50]));


//////            selectedGraphic.setSymbol(highlightSymbol);
//////            selectedGraphic.show();
//////        }

//////        //dojo.style(r, {"backgroundColor": "#F5F5F5"});
//////        //dojo.style(r, { "border": "solid 1px red"});
//////        //r.style.border = "solid 1px red";

//////        return
//////    } catch (Err) {
//////        console.debug("Error:" + Err);
//////    }
//////}

//////// Remove feature highlight when mouse goes off the corresponding grid row
//////function onRowMouseOut(r, index) {

//////    try {

//////        //var selectedGraphic = map.graphics.graphics[index];
//////        var selectedGraphic = parcelGraphics[index];
//////        if (selectedGraphic != null) {
//////            selectedGraphic.setSymbol(parcelHighlightSym);
//////            //selectedGraphic.hide();
//////        }

//////        //r.style.border = "none 1px red";

//////        return
//////    } catch (Err) {
//////        console.debug("Error:" + Err);
//////    }
//////}

//////function showDetails(index) {

//////    // zoom to the graphic and highlight
//////    try {
//////        console.debug("Zoom to: " + index);
//////        var selectedGraphic = parcelGraphics[index];

//////        if (selectedGraphic != null) {
//////            zoomMap(selectedGraphic.geometry.getExtent().expand(1.3));
//////            map.graphics.clear();
//////            map.graphics.add(selectedGraphic);
//////            dojo.byId("results-details-content").innerHTML = selectedGraphic.getContent();
//////            detailGraphic = selectedGraphic;
//////            searchResults_show("details");
//////        }
//////    }

//////    catch (Err) {
//////        console.debug(Err)
//////    }
//////}

//////function goBacktoResults() {

//////    try {

//////        // reselect the parcels
//////        printResults();

//////        // show the results
//////        showPanel("results");
//////    } catch (Error) {
//////    console.debug("Error in 'goBacktoResults' function");
//////    console.debug(Error);
//////    }

//////}

//////function clearSearchResultsPanel() {

//////    // reset the global variables
//////    detailGraphic = null;
//////    parcelGraphics = [];
//////    currentResultsSet = null;
//////    bufferGraphics = null;
//////    additionalFields = [];


//////    // reset the large grid
//////    dojo.style("resultsetbutton", { display: "none" });
//////    //dojo.byId("gridNode").innerHTML = "";

//////    // clear the node
//////    dojo.byId("grid").innerHTML = "";
//////    dojo.byId("pager").innerHTML = "";

//////}


//////function zoomTo(index, show) {

//////    try {
//////        console.debug("Zoom to: " + index);
//////        var selectedGraphic = parcelGraphics[index];


//////        if (selectedGraphic != null) {
//////            zoomMap(selectedGraphic.geometry.getExtent().expand(1.3));

//////            if (show) {
//////                // calculate the height/width
//////                var windowWidth = 250;
//////                var windowHeight = 300;

//////                if (map.height < 300) {
//////                    showPanel("details-sidebar");
//////                    dojo.byId("details-sidebar-content").innerHTML = selectedGraphic.getContent();
//////                    dojo.byId("details-sidebar-header").innerHTML = selectedGraphic.getTitle();
//////                }
//////                else {
//////                    var windowHeight = goodHeight;
//////                    var dHeight = (map.height / 2) - 50;


//////                    if (windowHeight > dHeight)
//////                        windowHeight = dHeight;

//////                }

//////                zoomAfterLoadEvntHandle = dojo.connect(map, "onExtentChange", showInfoWindowAfterZoom);
//////                map.infoWindow.setContent(selectedGraphic.getContent());
//////                map.infoWindow.setTitle(selectedGraphic.getTitle());
//////                map.infoWindow.resize(windowWidth, windowHeight);
//////            }
//////        }
//////    }
//////    catch (Err) {
//////        console.debug(Err)
//////    }
//////}

//////function zoomToResultbyIndex(indx) {
//////    if (currentResultSet != null) {
//////        var graphic = currentResultSet.features[indx];
//////        if (graphic != null) {
//////            try {
//////                var parcels_content = getParcelContent(graphic);
//////                infoTemplate = new esri.InfoTemplate(parcels_title_content, parcels_content);

//////                //Add result feature to map
//////                graphic.setSymbol(parcelHighlightSym);
//////                graphic.setInfoTemplate(infoTemplate);
//////                map.graphics.clear();
//////                map.graphics.add(graphic);

//////                zoomGraphic(graphic, true);
//////                dijit.byId("TaxCardReport").hide();
//////                dojo.style("resultsetbutton", { display: "block" });
//////            } catch (Err) {
//////                console.debug(Err)
//////            }
//////        } // if graphic is not null
//////    } // if current results set is not null
//////} // end function


//////function zoomGraphic(selectedGraphic, show) {
//////    if (selectedGraphic != null) {
//////        zoomMap(selectedGraphic.geometry.getExtent().expand(1.3));

//////        if (show) {
//////            // calculate the height/width
//////            var windowWidth = 250;
//////            var windowHeight = 300;
//////            if (map.height < 300) {
//////                showPanel("details-sidebar");
//////                dojo.byId("details-sidebar-content").innerHTML = selectedGraphic.getContent();
//////                dojo.byId("details-sidebar-header").innerHTML = selectedGraphic.getTitle();
//////            }
//////            else {
//////                var windowHeight = goodHeight;
//////                var dHeight = (map.height / 2) - 50;
//////                if (windowHeight > dHeight)
//////                    windowHeight = dHeight;
//////            }

//////            zoomAfterLoadEvntHandle = dojo.connect(map, "onExtentChange", showInfoWindowAfterZoom);
//////            map.infoWindow.setContent(selectedGraphic.getContent());
//////            map.infoWindow.setTitle(selectedGraphic.getTitle());
//////            map.infoWindow.resize(windowWidth, windowHeight);
//////        }
//////    }

//////}

//////var zoomAfterLoadEvntHandle;
//////function showInfoWindowAfterZoom() {
//////    // show the info window
//////    try {
//////        var pt = map.extent.getCenter();
//////        var spt = map.toScreen(pt)
//////        if (spt != null) {
//////            map.infoWindow.show(spt, map.getInfoWindowAnchor(spt));
//////        }
//////    }
//////    catch (Err) { console.debug(Err); }
//////    dojo.disconnect(zoomAfterLoadEvntHandle);
//////}

//////function exportExcel() {


//////    try {

//////        var results = currentResultSet.features;
//////        var items = []; //all items to be stored in data store
//////        dojo.forEach(results, function(feature, index) {
//////            items.push(feature.attributes);  //append each attribute list as item in store
//////        });

//////        //create data object to be used in store
//////        var data = {
//////            identifier: "CYPAR",
//////            items: items
//////        };

//////        console.debug("finished creating the data store");

//////        //esri.config.defaults.io.proxyUrl = "proxy.ashx";
//////        //esri.config.defaults.io.alwaysUseProxy = false;
//////        esri.request({
//////            url: dataHandlerURL,
//////            postData: dojo.toJson(data),
//////            handleAs: "json",
//////            callbackParamName: "callback",
//////            load: function(response, io) {
//////                searchWin = window.open(response.href, "ExportFile");
//////                if (searchWin.opener == null)
//////                    searchWin.opener = self;
//////            
//////            },
//////            error: function(error) {
//////                alert(error.message);
//////            }
//////        }, true);


//////    } catch (error) {

//////        var yy = [];
//////        console.debug(error);
//////        yy.push("An Error Occured in the Application...");
//////        yy.push("<div>" + error.message + "</div>");
//////        dojo.forEach(error.details, function(detail) {
//////            yy.push("<div>" + detail + "</div>");
//////        });

//////        dojo.byId("info").innerHTML = yy.join("");
//////        showPanel("info");


//////    }

//////}

//////function showGrid(results) {
//////    map.graphics.clear();
//////    var dataforGrid = [];

//////    var results = currentResultSet.features;
//////    var items = []; //all items to be stored in data store
//////    dojo.forEach(results, function(feature, i) {

//////        var graphic = feature;
//////        var attValues = [];
//////        attValues.push(i);
//////        console.debug(graphic.attributes);
//////        var featureAttributes = graphic.attributes;
//////        for (att in featureAttributes) {
//////            if (dojo.indexOf(parcels_table_fields, att) > -1) {
//////                attValues.push(featureAttributes[att]);
//////                console.debug(att);

//////            }
//////        }

//////        dataforGrid.push(attValues); //push attributes into the array, one row at a time


//////    });

//////    var h = map.height;
//////    var w = map.width + 260;
//////    dojo.style('gridNode', { height: h + "px" });
//////   

//////    var model = new dojox.grid.data.Table(null, dataforGrid);

//////    var layout = [gridview1];
//////    gridWidget.setModel(model);
//////    gridWidget.setStructure(layout);
//////    dijit.byId("TaxCardReport").show();
//////}









//////// #################################################################################
////////  Show Google Street View
//////function showGoogleStreetViewByIndex(indx) {
//////    var graphic = currentResultSet.features[indx];
//////    if (graphic != null) {
//////        showGoogleStreetView(graphic);
//////    }
//////}
//////function showGoogleStreetView(graphic) {
//////    try {
//////        console.debug(graphic);
//////        var pt = graphic.geometry.getExtent().getCenter();
//////        var ptGraphic = new esri.Graphic(pt);
//////        gsvc = new esri.tasks.GeometryService(geoServiceUrl);
//////        // out spatial reference is WGS-84
//////        var outSR = new esri.SpatialReference({ wkid: 4326 });
//////        gsvc.project([ptGraphic], outSR, function(features) {
//////            pt = features[0].geometry;
//////            var url = "http://maps.google.com/maps?ll=${latt},${long}&spn=0,359.159546&z=11&layer=c&cbll=${latt},${long}&cbp=12,0,,0,5";
//////            url = esri.substitute({ latt: pt.y, long: pt.x }, url);
//////            window.open(url);
//////        });
//////    } catch (Error) {
//////    console.debug(Error);
//////    }
//////}


