// #########################################################################
//  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 _parcelStore = null;
var allSelectionSymbol, allSelectionGraphics;


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);

//            dojo.connect(allSelectionGraphics, "onClick", function(e) { console.debug("All Selection Graphic is clicked"); console.debug(e.graphic) });
//            dojo.connect(map.graphics, "onClick", function(e) { console.debug("map graphics is clicked"); console.debug(e.graphic) });



            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 {
        console.debug(results);
        bulletGraphics.clear();
        parcelGraphics.clear();
        _parcelStore = null;

        currentResultSet = results;
        _currentIndex = 0;
        _totalRecords = results.features.length;

        console.debug(_totalRecords);

        switch (_totalRecords) {
            case 0:
                // go back
                dojo.byId("back").innerHTML = "<a href=\"#\" onmousedown=\"showSearchPanel('" + returnToPanel + "');\">Refine Search Parameters</a>";
                dojo.byId("grid").innerHTML = "<p>Sorry, but your query returned no results from the database</p><p>The query Attempted was: <br/>" + txtWhereClause + "</p>";
                showSearchPanel("results");
                return false;
                break;
            case 1:
                parcelGraphics.show();
                //console.debug("cursor: " + i);
                var graphic = results.features[0];
                parcelGraphics.add(graphic);
                showDetails(0);
                break;
            default:
                
                if (returnToPanel === "advanced") {
                    dojo.byId("back").innerHTML = "<a href=\"#\" onmousedown=\"showPanel('advanced');\">Refine Search Parameters</a>";
                    returnToPanel = "about";
                } else {
                    dojo.byId("back").innerHTML = "";
                }
                
                _initPagerSettings(results);
                showAllSelected();
                printResults();
                zoomToSelected();
                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>";
            //dojo.byId("results-details-header").innerHTML = "<div><button dojoType=\"dijit.form.Button\" label=\"Back to Search Results\" iconClass=\"iconReset\" onClick=\"goBacktoResults\"></button></div>";
        } else {
            dojo.byId("results-details-header").innerHTML = "<div class=\"captionbr\">Search Results</div>";
        }
    }
    showSearchPanel("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 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 = dijits.custom.Parcels.getBrief(graphic, j);
        infoTemplate = new esri.InfoTemplate(parcels_title_content, 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, "onMouseMove", function(evt) {
//            var g = evt.graphic;
//            map.infoWindow.setContent(g.getContent());
//            map.infoWindow.setTitle(g.getTitle());
//            map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
//        });
//        dojo.connect(bulletGraphics, "onMouseOut", function() { map.infoWindow.hide(); });
//  
        // 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 = graphic.getContent();
            rowText += "<td><div class=\"detail-section\">" + rowContent + "</div></td></tr>";

        } else {
            rowText = dijits.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) {
    var s = [];
    s.push("<table width=\95%\"><tbody><tr><td class=\"captionbr\">Search Results</td><td align=\"right\">");
    s.push("</td><tr></tbody></table>");
    s.push("<div>" + _totalRecords + " Features Found." + blank + "(page " + currentPage + " of " + _totalPages + ")</div>");

    if (_totalRecords == 500)
        s.push("<div class=\"error\">Maximum number of records returned, please refine your search</div>");



    return s.join("");

//    dojo.byId("totalPages").innerHTML = _totalPages;
//    dojo.byId("totalRecords").innerHTML = _totalRecords;
//    dojo.byId("currentPage").innerHTML = currentPage;
}

function _resultsToolbar() {

    var s = [];
    s.push("<div class=\"gray\">");
    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:showGridResultsPage();\">Show as Table</a></div>");
    s.push("</td></tr>");
    s.push("</tbody></table>");
    s.push("</div>");
    
    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;
        dojo.byId("pager-top").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 = dijits.custom.Parcels.getDetails(detailGraphic);
            infoTemplate = new esri.InfoTemplate(parcels_title_content, 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);
                    });
                    
                    //
                    zoomMap(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 {

        // 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
        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) {
            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[fields.keyfield]
            prevSelected.push(id);
        });

        console.debug(prevSelected);

        dojo.forEach(results.features, function(graphic) {
            var id = graphic.attributes[fields.keyfield];
            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() {

    dijits.custom.Parcels.Export(currentResultSet.features);
    
}


function showGridResultsPage() {

    var items = dijits.custom.Parcels.getDataStore(currentResultSet.features);

    //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();
    
}







// #################################################################################
//  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);
    }
}

