// #########################################################################
//  Search Results:
//
//  Global Variables:
//      currentResultSet
//      currentIndex
//
//  Functions:
//      showParcelSearchResults:
//      goPreviousResults
//      goNextResults
//      printResults
//      onRowMouseOver
//      onRowMouseOut
//      zoomTo: Zoom to an index
//      zoomToSelected: Zooms the the Extent of the AllSelection Graphic layer
//      convertFindResult2FeatureSet: If the search is a Find Task, then convert the resuts to a featureSet.
//      clearSearchResults: Clears all the graphics layers & sets the html elements to nothing
//      hideSearchResults: hides the results graphics 
//      showSearchResults: shows the results graphics [AllSelection, Selection, & Buffer]
//
//      getParcelTooltipContent: 
// ##########################################################################

var currentResultSet, currentIndex;

var selectionSymbol =  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, 250, 202, 0.50]));
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]));

var allSelectionSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 255, 255]), 2);
                                   

var selectionGraphics, bufferGraphics, allSelectionGraphics;

var showExceedDialog = true;

var parcelStore;
var sortKeys = [];

function showParcelSearchResults(results) {

    currentResultsPanel = "RESULTS";

    try {

        dojo.style("maxrecordmessage", { display: "none" })

        selectionGraphics.clear();
        allSelectionGraphics.clear();
        
        currentResultSet = results;
        currentIndex = 0;
        if (results.features.length == 0) {
            var yy = [];
            var returnToCmd = "showPanel('" + returnToPanel + "')";
            yy.push("<p><a href=\"#\" onmousedown=\"" + returnToCmd + "\"><img src=\"images/jpgs/search_again.jpg\" title=\"Search Again?\"/></a></p>");
            yy.push("<p class=\"attention\">Sorry, but your query return no results from the database</p>");
            dojo.byId("grid").innerHTML = yy.join("");
            showPanel("RESULTS");
            return false;
        } else if (results.features.length == 1) {
            // zoom to the feature and show tax card
            var graphic = results.features[0];
            graphic.setSymbol(highlightSymbol);
            selectionGraphics.add(graphic);
            selectionGraphics.show();

            


            // get the PID
            showParcelDetail(graphic);

        } else {

            // determine the number of pages...
            maxPage = 1
            if (results.features.length <= 10)
                maxPage = 1;
            else {

                if ((results.length % 10) == 0)
                    maxPage = Math.round((results.features.length / 10));
                else
                    maxPage = Math.round((results.features.length / 10)) + 1;
            }


            if (results.features.length == 500) {
                doQueryCount();
            }

            // create the spatial store
            parcelStore = createSpatialStore(currentResultSet, parcelFields);

            // do the default sort
            if (sortKeys.length == 0)
                sortKeys = [{ attribute: "owner", ascending: true}];

            // print the search results panel
            printResults();

            // zoom to the selected set
            zoomToSelected();
          
            
        
        }
    } catch (error) {
    console.debug("An Error occured in the application, in routine 'showParcelSearchResults'");
    console.debug(error);
    showError("", error);

    }


}

function doExcelReport() {

    try {

        //create data object to be used in store
        var data = {
            action: "export",
            where: dojo.toJson(parcelQuery.where),
            SelectedPID: parcelQuery.selectedPID,
            x: parcelQuery.x,
            y: parcelQuery.y,
            radius: parcelQuery.radius        
        };

        var iframeDocument = dojo.isIE ? printingHiddenFrame.contentWindow.document : printingHiddenFrame.contentDocument;
        iframeDocument.getElementById("data").value = dojo.toJson(data);
        iframeDocument.getElementById("export").submit();

    } catch(ex) {
    
        alert(ex.message);
    
    }

//    esri.request({
//        url: parcelDataHandlerURL,
//        postData: dojo.toJson(data),
//        handleAs: "json",
//        callbackParamName: "callback",
//        load: function(response, io) {

//            if (response.href != "") {
//                searchWin = window.open(response.href, "ExportFile");
//                if (searchWin.opener == null)
//                    searchWin.opener = self;
//            } else {
//                alert("we're sorry, but there was a problem processing your request");
//            }
//        },
//        error: function(error) {
//            alert(error.message);
//        }
//    }, true);


}

function doQueryCount() {

    //create data object to be used in store
    var data = {
        action: "count",
        where: dojo.toJson(parcelQuery.where),
        SelectedPID: parcelQuery.selectedPID,
        x: parcelQuery.x,
        y: parcelQuery.y,
        radius: parcelQuery.radius
    };

    dojo.style("maxrecordmessage", { display: "block" })
    url = parcelDataHandlerURL;

    esri.request({
        url: parcelDataHandlerURL,
        postData: dojo.toJson(data),
        handleAs: "json",
        callbackParamName: "callback",
        load: function(response, io) {
            console.debug(response);
            var ct = response.count;

            if (ct == undefined) { ct = "unknown";}
                

            dojo.byId("maxrecordcount").innerHTML = ct + " Total Records found in the GIS Database";

            if (showExceedDialog) {
                dojo.byId("MaxRecordCount").innerHTML = ct;
                dijit.byId("MaxRecordDialog").show();
            }

            showExceedDialog = false;
        },
        error: function(error) {
            alert(error.message);
        }
    }, true);
    
   


}


function goPreviousResults() {
    currentIndex = currentIndex - 1
    printResults();
}

function goNextResults() {
    currentIndex = currentIndex + 1;
    printResults();
}

function printResults() {
    selectionGraphics.clear();
    selectionGraphics.show();

    var results = currentResultSet;
    var startIndex = currentIndex * 10;
    var endIndex = (currentIndex + 1) * 10;
    if (results.features.length < endIndex)
        endIndex = results.features.length;

    var totalRec = results.features.length;
    var pageNumber = currentIndex + 1;

   


    var s = [];

    




    // refine search
    var returnToCmd = "showPanel('" + returnToPanel + "')";
        
    // begin the results table...
    s.push("<div class=\"gray\">");
    s.push("<Table border='0' cellpadding='2' cellspacing='2' width='100%'>");
    s.push("<tr><td colspan='4' class='Bar' height='20'><b>Search Results</b></td></tr>");
    if (totalRec < endIndex)
        s.push("<tr><td colspan='4'>Records: " + (startIndex + 1) + " to " + endIndex + " of " + totalRec + ".</td></tr>");
    else
        s.push("<tr><td colspan='4'>Records: " + (startIndex + 1) + " to " + endIndex + " of " + totalRec + ".</td></tr>");

    if (totalRec > 1)
        s.push("<tr><td colspan='4'>Click on Parcel ID to select parcel.</td></tr>");

    s.push("<tr><td class='Bar' height='20' colspan=\"4\"><center>");
    s.push("<a href=\"#\" onmousedown=\"" + returnToCmd + "\"><img src=\"images/jpgs/search_Again.jpg\"/></a>");
    s.push("<a href=\"javascript:\zoomToSelected();\"><img src=\"Images/jpgs/Zoom_to_All_Selected.jpg\" title=\"zoom to all selected\"/></a>");
    s.push("<a href=\"javascript:\ToolbarMouseDown('ClearSelection', 'Command');" + returnToCmd + "\"><img src=\"images/jpgs/clear_selection.jpg\" title=\"clear selection\"/></a>");
    s.push("</center></td></tr>");


    //WRITE COLUMN HEADINGS
    s.push("<tr><td class=\"Bar\" height='20'><b>REC</b></td><td class='Bar' width='60'><b>PARCEL ID</b></td><td class='Bar'><b>OWNER</b></td><td class='Bar'><b>PROPERTY ADDRESS</b></td></tr>");

    var content = [];

    var indx = 0;
    
    parcelStore.fetch({
        sort: sortKeys,
        onItem: function(item) {

            if (!parcelStore.hasAttribute(item, "endOfFile")) {
                try {

                    if ((indx < endIndex) && (indx >= startIndex)) {

                        //Get the values out of the store
                        var id = parcelStore.getValue(item, "id");
                        var pin = parcelStore.getValue(item, "pid");
                        var owner = parcelStore.getValue(item, "owner");
                        var prop_add = parcelStore.getValue(item, "address");
                        var graphic = parcelStore.getValue(item, "graphic");   
                        var pos = indx + 1;
                        
                        // Add the Graphic
                        graphic.setSymbol(selectionSymbol);
                        selectionGraphics.add(graphic);
                
                        // create the content
                        var cssClass = "Row1";
                        if (indx % 2 == 0)
                            cssClass = "Row2";

                        content.push("<tr onmouseover=\"onRowMouseOver(" + id + ");\" onmouseout=\"onRowMouseOut(" + id + ");\" class=\"" + cssClass + "\"><td  height='20' align='center'><a href=\"#\" onmousedown=\"zoomTo(" + id + ");\" alt=\"zoom to\"/>" + pos + "</a></td><td><a href=\"#\" onmousedown=\"showParcel('" + pin + "');\">" + pin + "</a></td><td>" + owner + "</td><td>" + prop_add + "</td></tr>");
                    }
                    indx++


                } catch (ex) {
                    console.warn("An error occurred in processing...", ex);
                }

            }
        },
        onError: function(error) {

            content = [];
            content.push("<tr><td colspan=\"5\">An Error occurred in processing</td></tr>");

        }

    });

    s.push(content.join(""));


    if (endIndex > 10)
        s.push("<tr><td colspan=\"4\" align=\"center\"><a href=\"#\" onmousedown=\"Javascript:goPreviousResults();\"><img src='images/b_previous.gif' border='0'></a>");
    else
        s.push("<TR><TD colspan='4' align='center'><img src='images/b_previous_off.gif' border='0'>");

    s.push("<img src='images/b_blank.gif' border='0'>");
    if (totalRec > endIndex)
        s.push("<a href=\"#\" onmousedown=\"goNextResults();\"><img src='images/b_next.gif' border='0'></a></td></tr>");
    else
        s.push("<img src='images/b_next_off.gif' border='0'></td></tr>");

//    s.push("</tbody></table></div>");

    if (txtWhereClause != null) {
//        s.push("<div style=\"margin:7px\">");
//        s.push("<b>Your Search Query was:</b>");
//        s.push("<br/>" + txtWhereClause);
        //        s.push("<br/>");

        s.push("<tr><td colspan='4'>");

        s.push("<div style=\"margin:7px\">");
        s.push("<b>Your Search Query was:</b>");
        s.push("<br/>" + txtWhereClause);
        s.push("<br/>");
        s.push("</td></tr>");

    }

    if (parcelQuery != null) {

//        var reportLinkCmd = "parceldatahandler.ashx?action=export&outputtype=EXCEL" + parcelQuery.getReportQueryString();
//        s.push("<p>Export the Result set to <a href=\"" + reportLinkCmd + "\" target=\"_blank\">excel</a></p>");

        s.push("<tr><td colspan='4'>");

          var reportLinkCmd = "javascript:doExcelReport();";
          s.push("<a href=\"" + reportLinkCmd + "\" ><img src=\"images/jpgs/excel.jpg\" title=\"export to excel\"/></a></p>");

          s.push("</td></tr>");
      }

    s.push("</tbody></table></div>");

    dojo.byId("grid").innerHTML = s.join("");

    map.graphics.enableMouseEvents();

    showPanel('RESULTS');

}


// Highlight the feature when the mouse hovers over the corresponding grid row
function onRowMouseOver(index) {

    try {
        var selectedGraphic = allSelectionGraphics.graphics[index];
        if (selectedGraphic != null) {
            if (selectedGraphic.getDojoShape()) {
                selectedGraphic.setSymbol(highlightSymbol);
            }
         }  
            
        
    } catch (Error) {console.warn("An error occurred onRowMouseOver on " + index, Error);}

    return

}

// Remove feature highlight when mouse goes off the corresponding grid row
function onRowMouseOut(index) {

    try {
       
        var selectedGraphic = allSelectionGraphics.graphics[index];

        if (selectedGraphic != null) {
            if (selectedGraphic.getDojoShape()) {
                selectedGraphic.setSymbol(selectionSymbol);
            }
        }
    } catch (Error) { console.warn("An error occurred onRowMouseOut  on " + index, Error); }
    return
}


function zoomToSelected() {

    try {
        var fullExt = esri.graphicsExtent(currentResultSet.features);
        if (fullExt != null)
             map.setExtent(fullExt.expand(1.1));
        showAllSelected();    
            
    } catch (Error) {
    console.warn("An Error occurred in the application in routine 'zoomToSelected'", Error);

    }
}

function showAllSelected() {

    try {
        allSelectionGraphics.clear();

        dojo.forEach(currentResultSet.features, function(graphic) {
            var g = new esri.Graphic(graphic.toJson())
            g.setSymbol(allSelectionSymbol);
            allSelectionGraphics.add(g);
        });

        allSelectionGraphics.show();
    
    } catch(Error) {
        console.warn("An error occurred in 'showAllSelected' function", Error);
    }
}

function zoomTo(index) {

    try {
        console.debug("Zoom to: " + index);
        var selectedGraphic = allSelectionGraphics.graphics[index];

        if (selectedGraphic != null) {
            zoomMap(selectedGraphic.geometry.getExtent().expand(1.5));
        }
    }
    catch (Err) {
        console.debug(Err)
    }
}


// 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);
}

function clearSearchResults() {
    try {
        allSelectionGraphics.clear();
        selectionGraphics.clear();
        currentResultSet = null;
        parcelQuery.clearQuery();
        
        dojo.byId("grid").innerHTML = "";
        dojo.byId("pager").innerHTML = "";
        dojo.byId("taxcard-backbutton").innerHTML = "";
    } catch (Error) {
        console.debug("An error occurred in function: clearSearchResults");
        console.debug(Error);   
    }
}

function hideSearchResults() {
    allSelectionGraphics.hide();
    selectionGraphics.hide();
    bufferGraphics.hide();
}

function showSearchResults() {
    allSelectionGraphics.show();
    selectionGraphics.show();
    bufferGraphics.show();
}

function getParcelTooltipContent(graphic) {

    var featureAttributes = graphic.attributes;

    var s = [];
    s.push("<div class=\"gray\">");
    s.push("<table cellspacing=\"1\" cellpadding=\"1\" border=\"0\" width=\"95%\"><tbody>");
    s.push("<tr><td class=\"Bar\" width=\"48%\">FieldName</td><td class=\"Bar\">Value</td></tr>");

    for (att in featureAttributes) {

        var showIt = true;
        dojo.forEach(fieldsNotToShow, function(fld) { if (fld.toUpperCase() == att.toUpperCase()) showIt = false });

        if (showIt) {
            //console.debug(att);
            var isSpecial = false;
            dojo.forEach(specialFields, function(fld) { if (fld.toUpperCase() == att.toUpperCase()) isSpecial = true });


            var value = featureAttributes[att];
            if (value == "Null")
                value = "";
            switch (att.toUpperCase()) {
                case "PID":
                    s.push("<tr><td class='Row1' width='100' height='30' align=\"right\"><b>Parcel ID</b></td>");
                    var pin = value
                    cmd = "showParcel(\"" + pin + "\", true)";
                    console.debug(cmd);
                    s.push("<td class=\"Row2\" width=\"200\" height=\"30\"><a href=\"#\" onmousedown='" + cmd + "'>Show Tax Card</a></td>");
                    s.push("</tr>");

                    break;
                default:
                    s.push("<tr><td class=\"Row1\" width=\"50%\" align=\"right\"><b>" + att + ":<b>&nbsp;</td><td class=\"Row2\" width=\"50%\" align=\left\">" + value + "<td/></tr>");
                    break;
            }

        }

    }

    s.push("</tbody></table></div>");
    return s.join("");
    
}

function setSort(att, isDesc) {
    
    if (isDesc) 
        sortKeys = [{ attribute: att, ascending: true}];
    else
        sortKeys = [{ attribute: att, descending: true}];
}

function createSpatialStore(results, fields) {

    var items = [];

    dojo.forEach(results.features, function(f, indx) {

        var item = { id: indx,
            pid: getFieldValue(f, fields.PID),
            owner: getFieldValue(f, fields.OWNER),
            address: getFieldValue(f, fields.ADDRESS),
            graphic: f
        }
        console.debug(item);
        items.push(item);
    });


    //Create data object to be used in store
    var data = {
        identifier: "id", //This field needs to have unique values
        items: items
    };

    //Create data store and bind to grid.
    var store = new dojo.data.ItemFileReadStore({
        data: data
    });

    return store;

}

