﻿// #########################################################################
//  Search Results:
// ##########################################################################

var parcelGraphics, bulletGraphics;

var detailGraphic;
var bufferGraphics;
var currentResultSet;
var _currentIndex, _totalRecords, _totalPages;
var _RecsPerPage = 10;
var _isDetailView = true;
var _parcelStore = null;
var allSelectionSymbol, allSelectionGraphics;
var searchCompleted = false;

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);

        dojo.connect(parcelGraphics, "onClick", function(e) { console.debug("ParcelGraphic is clicked"); console.debug(e.graphic) });

        bulletGraphics = new esri.layers.GraphicsLayer({ id: "bullets", displayOnPan: dojo.isIE ? false : true })
        map.addLayer(bulletGraphics);

        allSelectionGraphics = new esri.layers.GraphicsLayer({ id: "allSelectionResults", displayOnPan: dojo.isIE ? false : true })
        map.addLayer(allSelectionGraphics);

        allSelectionSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 2);

        // 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.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 255, 0]), 3);

        parcelHoverSymbol =
                  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 {
        searchCompleted = false;
        console.debug(results);
        bulletGraphics.clear();
        parcelGraphics.clear();
        allSelectionGraphics.clear();
        _parcelStore = null;

        currentResultSet = results;
        _currentIndex = 0;
        _totalRecords = results.features.length;

        hideSearchResultsPanel();

        switch (_totalRecords) {
            case 0:
                // go back
                var yy = [];
                var returnToCmd = "showPanel('search');showSearchPanel('" + returnToPanel + "');";
                yy.push("<p><a href=\"#\" onmousedown=\"" + returnToCmd + "\">Search Again?</a></p>");
                yy.push("<p>Your search did not return any results</p>");               
                dojo.byId("info").innerHTML = yy.join("");
                showPanel("info");
                break;
            case 1:                
                parcelGraphics.show();
                var graphic = results.features[0];
                parcelGraphics.add(graphic);
                showDetails(0);
                
                break;
            default:
                _initPagerSettings(results);
                showAllSelected();
                printResults();
                zoomToSelected();
                break;
        }

        searchCompleted = true;
        console.debug("search is completed");

        return false;
        
    } catch (Error) {
        showSearchError("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 hideSearchResultsPanel() {
    dojo.style("results-details", { display: "none" });
    dojo.style("results-list", { display: "none" });
}

function searchResults_show(mode) {

    if (mode == "list") {

        allSelectionGraphics.show();
        parcelGraphics.show();
        bulletGraphics.show();
    
        dojo.style("results-details", { display: "none" });
        dojo.style("results-list", { display: "block" });

    } else {

        allSelectionGraphics.hide();
        parcelGraphics.show();
        bulletGraphics.hide();
    
        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>";
        }
    }
       
    showSearchPanel("results");
    showPanel("search");
}

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();
    
    _resultsHeader(currentPage);
 
    var s = [];
    if (!_isDetailView) {
        s.push("<div class=\"gray\"><table cellspacing=\"2\" cellpadding=\"2\" width=\"100%\" border=\"1\"><tbody>");
        s.push(custom.parcels.getRowHeader());
    } 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 displayGraphic = results.features[i];
        displayGraphic.setSymbol(parcelSelectedSymbol);

        //Clone the graphic...
        var graphic = new esri.Graphic(displayGraphic.toJson())

        // Create template for the info window
        var parcels_content = custom.parcels.getDetails(graphic, j);
        infoTemplate = new esri.InfoTemplate("Parcels", parcels_content);

        // add the graphic to the selection display without the infotemplate.
        parcelGraphics.add(displayGraphic);

        // apply the info template to the graphic that will not get added to the display array.
        graphic.setInfoTemplate(infoTemplate);

        // 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/markers/marker" + bNum + ".png"
        var mSym = new esri.symbol.PictureMarkerSymbol(bulletURL, 20, 34);
        var gPt = new esri.Graphic(centerPt, mSym, graphic.attributes, infoTemplate);
        bulletGraphics.add(gPt);

        dojo.connect(bulletGraphics, "onClick", function(evt) {
                var g = evt.graphic;
                var p = getInfoWindowHeight();
                map.infoWindow.setContent(g.getContent());
                map.infoWindow.setTitle(g.getTitle());
                map.infoWindow.resize(p.width, p.height);
                map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
        });
        
          
        // 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 + "\" /></td>";
            rowContent = custom.parcels.getBrief(graphic, j);
            rowText += "<td><div class=\"detail-section\">" + rowContent + "</div></td></tr>";

        } else {
            rowText = custom.parcels.getRow(graphic, j, cssClass);
        }
        s.push(rowText);

        j++
    } // end for


    s.push("</tbody></table></div>");


    if (_totalPages > 1) {
        _resultsFooter(currentPage, _totalPages);
        _showPager();
    }
    else {
        // hide the footer
        _hidePager();
    }



    // 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 showAllSelected() {

    try {
        allSelectionGraphics.clear();

        dojo.forEach(currentResultSet.features, function(graphic) {
            var g = new esri.Graphic(graphic.toJson())
            g.setSymbol(allSelectionSymbol);
            g.setInfoTemplate("", "");
            allSelectionGraphics.add(g);
        });

        allSelectionGraphics.show();

    } catch (Error) {
        console.warn("An error occurred in 'showAllSelected' function", Error);
    }
}

function _resultsHeader(currentPage) {
      

    if ( _totalRecords == 500)
        dojo.byId("maxRecords").style.display = "block"
    else
        dojo.byId("maxRecords").style.display = "none";
    
    dojo.byId("totalRecords").innerHTML = _totalRecords + " Features Found." + blank + "(page " + currentPage + " of " + _totalPages;
    

 }

function _resultsFooter(currentPage, totalPages) {

    try {

        // print the paging information at bottom...
        var prevTag, nextTag;
        var footer = "";

        if (currentPage > 1)
            prevTag = "<a href=\"javascript:goPreviousResults();\">Previous</a>&nbsp;&nbsp;";
        else
            prevTag = blank;

        if (currentPage < totalPages)
            nextTag = "<a style=\"position:absolute;right:2px;\" href=\"#\" onmousedown=\"javascript:goNextResults();\">Next</a>";
        else
            nextTag = blank;
        footer = prevTag + nextTag;
        dojo.byId("pager").innerHTML = footer;

        // show the footer
        _showPager();

    } catch (Error) {
        console.warn("An Error occurred creating the footer...", Error);
        dojo.style("pager", { display: "none" });
    }

}

function _showPager() {
    dojo.style("pager", { display: "block" });
    //dojo.style("pager-top", { display: "block" });
}

function _hidePager() {
    dojo.style("pager", { display: "none" });
    //dojo.style("pager-top", { display: "block" });
}


// 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(parcelHoverSymbol);
            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 {
        detailGraphic = parcelGraphics.graphics[index];
        if (detailGraphic != null) {

            var parcels_content = custom.parcels.getDetails(detailGraphic);
            infoTemplate = new esri.InfoTemplate("", parcels_content);
            detailGraphic.setInfoTemplate(infoTemplate);
            dojo.byId("results-details-content").innerHTML = detailGraphic.getContent(); ;
            map.infoWindow.hide();
            if (detailGraphic.geometry != null) {
                // Create template for the info window
                try {

                    // 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);
                    });

                    //
                    com.js.map.utils.zoomMap(map,detailGraphic.geometry.getExtent().expand(1.3));
                } catch (Error) {
                    console.debug("error");
                }
            }

            searchResults_show("details");
        }
    }

    catch (Err) {
        console.debug(Err)
    }
}

function goBacktoResults() {

    try {
        // reselect the parcels
        printResults();

    } catch (Error) {
        console.debug("Error in 'goBacktoResults' function");
        console.debug(Error);
    }

}

function clearSearchResultsPanel() {

    try {

        hideTable();

        // reset the global variables
        detailGraphic = null;
        parcelGraphics.clear();
        bulletGraphics.clear();
        parcelGraphics.hide();
        bulletGraphics.hide();
        allSelectionGraphics.clear();
        allSelectionGraphics.hide();
        currentResultSet = null;
        bufferGraphics = null;
        additionalFields = [];

        // reset the large grid
        //dojo.style("resultsetbutton", { display: "none" });


        // clear the node
        hideSearchResultsPanel();
        dojo.byId("back").innerHTML = "";
        dojo.byId("grid").innerHTML = "<p><strong>No Search Results</strong></p>";
        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) {
            com.js.map.utils.zoomMap(map, selectedGraphic.geometry.getExtent().expand(1.3));

            if (show) {

                var p = getInfoWindowHeight();                               
                var zoomAfterLoadEvntHandle;
                zoomAfterLoadEvntHandle = dojo.connect(map, "onExtentChange", function() {                
                
                    // 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);
                    map.infoWindow.setContent(selectedGraphic.getContent());
                    map.infoWindow.setTitle(selectedGraphic.getTitle());
                    map.infoWindow.resize(p.width, p.Height);                
                });
                
            } 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);
        }
    }

}




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["Parcel_ID"]
            prevSelected.push(id);
        });

        dojo.forEach(results.features, function(graphic) {
        var id = graphic.attributes["Parcel_ID"];
            if (dojo.indexOf(prevSelected, id) < 0) {
                features.push(graphic);
            }
        });

        currentResultSet.features = features;
        _totalRecords = currentResultSet.features.length;

        //
        _initPagerSettings(currentResultSet);
        goLastPage();
        showAllSelected();
    } catch (Error) { console.warn("error occurred in AddToSelectedGraphic:", Error); }


}



function exportExcel() {

    custom.parcels.Export(currentResultSet.features);
}


function showGridResultsPage() {

    //var items = custom.parcels.getDataStore(currentResultSet.features);


    var items = [];
    

    dojo.forEach(currentResultSet.features, function(f, indx) {

        var item = { id: indx,
            parcel_id: com.js.map.utils.getFieldValue(f, "Parcel_id"),
            ppn: com.js.map.utils.getFieldValue(f, "PPN_2"),
            owner1: com.js.map.utils.getFieldValue(f, "Owner1"),
            owner2: com.js.map.utils.getFieldValue(f, "Owner2"),
            saledate: com.js.map.utils.getFieldValue(f, "Sale_date"),
            saleprice: com.js.map.utils.getFieldValue(f, "Sale_Price"),
            acreage: com.js.map.utils.getFieldValue(f, "Total_Acres"),
            totalvalue: com.js.map.utils.getFieldValue(f, "Total_Value"),
            landvalue: com.js.map.utils.getFieldValue(f, "Land_Value"),
            bldgvalue: com.js.map.utils.getFieldValue(f, "Bldg_Value"),
            address: com.js.map.utils.getFieldValue(f, "Prop_Address"),
            featuretype: com.js.map.utils.getFieldValue(f, "FeatType")
        }
        items.push(item);
    });

   


    //Create data object to be used in store
    var data = {
        identifier: "id", //This field needs to have unique values
        items: items
    };

    


    dojo.connect(dojo.byId("closeTable"), "onmousedown", hideTable);
    dojo.connect(dojo.byId("closeTableimg"), "onmousedown", hideTable);

    //Create data store and bind to grid.
    jsonStore = new dojo.data.ItemFileReadStore({
        data: data
    });

    esriConfig.defaults.io.proxyUrl = "proxy.ashx";
    esriConfig.defaults.io.alwaysUseProxy = false;

    tableNode_grid.setStore(jsonStore);
    tableNode_grid.setQuery({ id: '*' });

    var h = getWindowHeight() - (35 + 50) + "px";
    
    dojo.style("grid_panel", { height: h }); 
    
    dojo.byId("TableNode").style.display = "block";

}

function hideTable() {

    dojo.byId("TableNode").style.display = "none";

}

function getWindowWidth() {
    var width = window.innerWidth;
    if (width == null) {
        if (document.documentElement && document.documentElement.clientWidth)
            width = document.documentElement.clientWidth
        else
            width = document.body.clientWidth;
    }
    return width;

}

function getWindowHeight() {
    var height = window.innerHeight;
    if (height == null) {
        if (document.documentElement && document.documentElement.clientHeight)
            height = document.documentElement.clientHeight;
        else
            height = document.body.clientHeight;
    }
    return height;
}




