﻿////////////////////////////////////////////////////////////////////////////////
/*
Date: 03/20/08
Reviewers: Dylan Thomas, Matt Hutchinson
Comments: Peer Review Notes - 2008.30.2 - Aralola Akinmade
•	Use a template when doing repetitive strings like building rows in a table.
•	http://extjs.com/deploy/ext/docs/output/Ext.Template.html
•	Ln 108
•	Isn't there a way to configure an action that happens for every AJAX call? Like displaying a "Loading..." dialog. Rather than doing it manually.
•	Can you handle exceptions somewhere in there? Like showing a generic error message. Ln 207 is an attempt.
•	Wrap the whole thing in a module so that the globals become properties or maybe fields in a constructor.
•	Ln 174 - rename j to fieldCounter or something. the i's and j's get confusing.
•	Ln 261, 308 - hardcoded CSS attributes (CustomNode implementation had issues with externally referenced CSS)
•	Ln 479 0 wow! that's cool. never seen it before.
•	Ln 546 - a bit more of a comment would be helpful - is this a parsed address, something else?
*/
////////////////////////////////////////////////////////////////////////////////
//globals
var contentThemesURL = "http://imaps.indygov.org/NeighborhoodService/NeighborhoodData.svc/search/ContentThemes";
var availableLayersURL = "http://imaps.indygov.org/NeighborhoodService/NeighborhoodData.svc/search/Layers/ADDRESS";
var layerDetailsURL = "http://imaps.indygov.org/NeighborhoodService/NeighborhoodData.svc/search/Layer/"; 
var addressURL = "http://imaps.indygov.org/NeighborhoodService/NeighborhoodData.svc/search/Location/";
var neighborhoodURL = "http://imaps.indygov.org/NeighborhoodService/NeighborhoodData.svc/search/Location/Neighborhoods/";
var xyURL = "http://imaps.indygov.org/NeighborhoodService/NeighborhoodData.svc/search/Location/";
var getNbrURL = "http://imaps.indygov.org/NeighborhoodService/NeighborhoodData.svc/search/LayerValues/CCGIS.IndyNeighborhoods/name";
var json;
var themesObj;
var layersObj;
var resultsObj;
var resultsTree;
var root;
var m_searchType;
var m_searchValue;
var m_neighborhood;
var header = "<span class='headertext'><b>Neighborhood Search Results</b></span>";
var m_feetInMile = 5280;
var m_distancesInFeet = [1320,2640,3960,5280,10560,15840,21120,26400];
var m_distancesInText = ["1/4 mile","1/2 mile","3/4 mile","1 mile","2 miles","3 miles","4 miles","5 miles"];

//======================================================================
//Generic Make AJAX call function
//======================================================================
function makeCall(operation,theUrl,searchValue, searchType)
{      
    //store the search type and value
    m_searchValue = searchValue;
    m_searchType = searchType;
    
    //kill the tree
    //if (resultsTree) resultsTree.destroy() ;
    
    //clear out the results obj
    resultsObj = null;
    
    //clear out the results panel
    Ext.get("ResultsPanel").dom.innerHTML = "";   
    Ext.get("ContentThemesPanel").dom.innerHTML = "";

    Ext.Ajax.request({
        url: "handlers/AJAXProxyHandler.ashx?cdurl=" + encodeURI(theUrl),
        timeout: 120000,

        //display the results on success
        success: function(response) {
            //evaluate the response
            if (resultsObj == null) {
                //resultsObj = eval("("+result+")");
                resultsObj = Ext.util.JSON.decode(response.responseText);
            }

            if (resultsObj.success == 'false') {
                Ext.MessageBox.show({
                    title: 'Status change',
                    msg: res.failmsg,
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }

            //Check to see if there are any address candidates
            if (resultsObj.Candidates) {
                if (resultsObj.Candidates.length > 1) {
                    //There are candidates
                    showCandidatesDialog(resultsObj.Candidates);
                    return;
                }
            }

            //display the results
            var str = "";
            if (resultsObj.Name) {
                //store the neighborhood name
                m_neighborhood = resultsObj.Name;

                switch (m_searchType) {
                    case "address":
                        str = header + "<p><span class=\"normaltext\">You searched for [<span class=\"boldtext\">" + m_searchValue + "</span>].</span>&nbsp;|&nbsp;";
                        str += "<span class=\"normaltext\">Neighborhood - <span class=\"boldtext\">" + resultsObj.Name + "</span>.</span><br />";
                        str += "<br/><a class=\"zoomlink\" href=\"javascript:top.zoomToPoint(";
                        str += resultsObj.Xcoord + "," + resultsObj.Ycoord + ",'" + m_searchValue + "');\">";
                        str += "<img src=\"images/buttons/showonmap.gif\" border=\"0\"> Zoom to " + m_searchValue + " on the map</a></p><hr size='1'>";

                        top.zoomToPoint(resultsObj.Xcoord, resultsObj.Ycoord, "'" + m_searchValue + "'");

                        break;
                    case "candidate":
                        str = header + "<p><span class=\"normaltext\">You searched for [<span class=\"boldtext\">" + m_searchValue + "</span>].</span>&nbsp;|&nbsp;";
                        str += "<span class=\"normaltext\">Neighborhood - <span class=\"boldtext\">" + resultsObj.Name + "</span>.</span><br />";
                        str += "<br/><a class=\"zoomlink\" href=\"javascript:top.zoomToPoint(";
                        str += resultsObj.Xcoord + "," + resultsObj.Ycoord + ",'" + m_searchValue + "');\">";
                        str += "<img src=\"images/buttons/showonmap.gif\" border=\"0\"> Zoom to " + m_searchValue + " on the map</a></p><hr size='1'>";

                        top.zoomToPoint(resultsObj.Xcoord, resultsObj.Ycoord, "'" + m_searchValue + "'");

                        break;
                    case "name":
                        str = header + "<p><span class=\"normaltext\">You searched for [<span class=\"boldtext\">" + m_searchValue + "</span>].</span>&nbsp;|&nbsp;";
                        str += "<span class=\"normaltext\">Neighborhood - <span class=\"boldtext\">" + resultsObj.Name + "</span>.</span><br />";
                        str += "<br/><a class=\"zoomlink\" href=\"javascript:top.zoomToExtent(";
                        str += resultsObj.MapExtent.XMIN + "," + resultsObj.MapExtent.YMIN + "," + resultsObj.MapExtent.XMAX + "," + resultsObj.MapExtent.YMAX + ");\">";
                        str += "<img src=\"images/buttons/showonmap.gif\" border=\"0\"> Zoom to " + m_neighborhood + " on the map</a></p><hr size='1'>";

                        top.zoomToExtent(resultsObj.MapExtent.XMIN, resultsObj.MapExtent.YMIN, resultsObj.MapExtent.XMAX, resultsObj.MapExtent.YMAX);

                        break;
                    case "xy":
                        str = header + "<p><span class=\"normaltext\">You clicked location [<span class=\"boldtext\">" + m_searchValue + "</span>].</span>&nbsp;|&nbsp;";
                        str += "<span class=\"normaltext\">Neighborhood - <span class=\"boldtext\">" + resultsObj.Name + "</span>.</span><br />";
                        str += "<br/><a class=\"zoomlink\" href=\"javascript:top.zoomToExtent(";
                        str += resultsObj.MapExtent.XMIN + "," + resultsObj.MapExtent.YMIN + "," + resultsObj.MapExtent.XMAX + "," + resultsObj.MapExtent.YMAX + ");\">";
                        str += "<img src=\"images/buttons/showonmap.gif\" border=\"0\"> Zoom to " + m_neighborhood + " on the map</a></p><hr size='1'>";

                        top.zoomToExtent(resultsObj.MapExtent.XMIN, resultsObj.MapExtent.YMIN, resultsObj.MapExtent.XMAX, resultsObj.MapExtent.YMAX);

                        break;
                    default:
                        break;
                }

                str += "Expand a category below to find out more about " + m_neighborhood + "<br/>&nbsp;<br/>";
                Ext.get("ResultsPanel").dom.innerHTML = str;

                //load the content themes
                displayContentThemes();

            } else {
                Ext.get("ResultsPanel").dom.innerHTML = "No matches were found";
            }

            //hide ajax loader                                
            hideResultsLoading();

        },

        failure: function(response) {
            //Load results into the DetailsPlaceHolder panel
            Ext.get("ResultsPanel").dom.innerHTML = "Your request [ " + searchValue + " ] could not be found.<br/>Please try a different search."; //response.responseText;                                       

            //hide ajax loader                                
            hideResultsLoading();

        },
        //params: regForm.getValues(),
        form: 'ResultsForm',
        method: operation

    });            
 }



//------------------------------------
// Display Content Themes as Nodes
//------------------------------------
function displayContentThemes()
{
        var Tree = Ext.tree;
        
        resultsTree = new Tree.TreePanel({
            el:'ContentThemesPanel',
            autoHeight: true,
            autoScroll:false,
            animate:true, 
            lines:false,           
            enableDD:false        
        });
        
        //alert(resultsTree);

        // set the root node
        root = new Tree.TreeNode({
            text: 'Neighborhood Information',
            draggable:false,
            expanded:true,
            id:'source'          
        });
        resultsTree.setRootNode(root);

        // render the tree
        resultsTree.render();    
                  
        //grab the contentthemes from the webservice
            Ext.Ajax.request({
               url: "handlers/AJAXProxyHandler.ashx?cdurl=" + encodeURI(contentThemesURL),
                timeout: 120000,
                     
                //display the results on success
                success: function(response) 
                {      
                
                    //build the content theme json object
                    themesObj = Ext.util.JSON.decode(response.responseText);
                    
                    //loop through the themes and create nodes on a tree
                    for (var i=0;i<themesObj.Items.length;i++)
                    {
                        for (var j=0;j<themesObj.Items[i].Fields.length;j++)
                        {
                            //grab the content theme name
                            var themeText = themesObj.Items[i].Fields[j].Value;
                            
                            //create the node
                            var themeNode = new Ext.tree.TreeNode({
                                        text: themeText,
                                        draggable:false,
                                        cls: "x-tree-node-theme",
                                        singleClickExpand:true,  
                                        expanded:false,                                      
                                        id:themeText
                                });
                                
                                
                           //add listener
                           //themeNode.on("click", loadThemeNodes);
                            
                            //add the node to the root
                            root.appendChild(themeNode);
                        }

                      resultsTree.syncSize();      

                    }
                    
                    //then run an ajax query to grab the layers
                    getAvailableLayers();
                                                                    
                },
                
                //on failure   
                failure: function(response)
                {
                    //TODO:
                }
             });       
                                                  
}
//-------------------------------------------
// When a layer node is clicked
//-------------------------------------------
function loadLayerDetails(node, e)
{   
    if (node.item(0).id == (node.id + "loading"))
    {             
        //check the search type    
        var theUrl = "";     
        if (m_searchType == "address" || m_searchType == "candidate")
        {
            theUrl = layerDetailsURL + node.text + "/" + m_searchValue + "/" + resultsObj.Xcoord + "/" + resultsObj.Ycoord;
        }else{
            theUrl = layerDetailsURL + node.text + "/" + m_neighborhood;
        }
     
        //Make call
        callLayerService(node,theUrl);

    }else{   
        //load the children
        //alert("You've already loaded " + node.text);
    }  
}

//-------------------------------------------
// Searches for all the layers that belong
// to the specified content theme
//-------------------------------------------
function preloadLayerNodes()
{
  if (layersObj)
  {
  
  //loop through the layers and add them to their corresponding parent nodes
  for (var i=0;i<layersObj.Items.length;i++)
  {
     var layerText = "";
     var themeText = "";
     var layerID = "";
                              
       for (var j=0;j<layersObj.Items[i].Fields.length;j++)
       {                
          
            var fieldName = layersObj.Items[i].Fields[j].Name.toUpperCase();
            
            //grab the layer name
            if (fieldName == "DISPLAYNAME")
            {        
                    layerText  = layersObj.Items[i].Fields[j].Value;        
            }
            if (fieldName == "THEMENAME")
            {                             
                    themeText  = layersObj.Items[i].Fields[j].Value;   
            }  
        
        }              
  
             //add the node
            if ((layerText != "") && (themeText != ""))
            {
                    //find the theme under the root and add the layer to it
                    var parentNode = root.findChild("id", themeText);
                    if (parentNode)
                    {                          
                        //if the layername is the same as its content theme
                        if (layerText == themeText){
                             layerID = layerText + "Information";
                        }else{
                            layerID = layerText;
                        }     
                    
                        var layerNode = new Ext.tree.TreeNode({
                                    text: layerText,
                                    draggable:false,
                                    cls:"mylayerstyle",
                                    singleClickExpand:true,  
                                    expanded:false,                                      
                                    id:layerID
                         });
                                                
                         //add listener
                         layerNode.on("click", loadLayerDetails);
                         layerNode.on("expand", loadLayerDetails);
                         
                        //Add the loading node to the layer
                        var loadingNode = new Ext.tree.TreeNode({
                                    records:"<img src='images/tree/loading.gif' />&nbsp;<i>loading details...</i>",
                                    draggable:false,
                                    expanded:true,
                                    leaf:true,   
                                    uiProvider:Ext.tree.customRecordNode,                                                     
                                    id:layerID+"loading"
                         });                                                        
                         layerNode.appendChild(loadingNode);  
                            
                         //add the node to the parent
                         parentNode.appendChild(layerNode);        
                    }
            }  
    }      
  }             
}
//-------------------------------------------
// Gets the available layers
//-------------------------------------------
function getAvailableLayers()
{
            //grab the layers from the webservice
            Ext.Ajax.request({
               url: "handlers/AJAXProxyHandler.ashx?cdurl=" + encodeURI(availableLayersURL),
               timeout: 120000,    
                   
                //load the layers on success
                success: function(response) 
                {                          
                    layersObj = Ext.util.JSON.decode(response.responseText);
                                       
                   //preload the child layer names
                   preloadLayerNodes();
                   resultsTree.syncSize();      
                   
                },
                
                //on failure   
                failure: function(response)
                {
                    //TODO:
                }
             });  
}
//-------------------------------------------------------
//Extending the Tree Nodes
//-------------------------------------------------------
Ext.tree.customRecordNode = function() {
	Ext.tree.customRecordNode.superclass.constructor.apply(this, arguments);
};

Ext.extend(Ext.tree.customRecordNode, Ext.tree.TreeNodeUI, {
	
	render : function(bulkRender)
	{ 
        var n = this.node; 
        var targetNode = n.parentNode ?  
              n.parentNode.ui.getContainer() : n.ownerTree.container.dom; 
        if(!this.rendered)
        { 
            this.rendered = true; 
            var a = n.attributes; 
             
          // add some indent caching, this helps performance when rendering a large tree
          this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
                         
           //var buf = ['<li class="x-tree-node"><span class="x-tree-node-indent">',this.indentMarkup,"</span>",a.records,"</li>"]; 
           var buf;
            buf = ['<li><span class="x-tree-node-indent-more">',this.indentMarkup,n.text,'</span>',a.records,"</li>"]; 
            if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
                this.wrap = Ext.DomHelper.insertHtml("beforeBegin",n.nextSibling.ui.getEl(), buf.join(""));
            }else{
                this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
            }
            
            this.elNode = this.wrap.childNodes[0]; 
            this.ctNode = this.wrap.childNodes[1]; 
            
            if (this.elNode)
            {
                var cs = this.elNode.childNodes; 
                this.indentNode = cs[0]; 
                this.ecNode = cs[1]; 
                this.iconNode = cs[2]; 
                this.anchor = cs[2]; 
                this.textNode = cs[2];
		        /**
		        * Added myCustomField
		        */
		        this.records = cs[3];
		        this.printInfo = cs[3];
            }
   
            }
       }, 
		
	getRecords : function(){
        return this.records;   
   }
});

function showResultsLoading() {
    var str = '<p class="extraPadding" style="text-align: left; vertical-align: middle;"><img src="images/loading.gif" alt="" />&nbsp;<img src="images/loading_text.gif" alt="" /></p>';    
    top.resetToolbar();
    Ext.get("LoadingResults").dom.innerHTML = str;
    top.portal.showResultsTab();
}

function hideResultsLoading() {
   top.resetToolbar();
    Ext.get("LoadingResults").dom.innerHTML = "";
    top.portal.showResultsTab();
}

//=================================================
//Search for a Neighborhood by Address
//=================================================
function findNeighborhoodByAddressWCF(address)
{

    // close help dialog if open
    top.portal.hideHelp();
     
    //show the results
    if (address != "")
    {   
        //netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        var urlString = addressURL + address;

        //show ajax loader                                
        showResultsLoading();
        
        makeCall("GET",urlString, address, "address");
        
   }else{
         alert("Please type in your address.");
   }
}

//=================================================
//Search for a Neighborhood by Name
//=================================================
function findNeighborhoodByNameWCF(name) 
{
    // close help dialog if open
    top.portal.hideHelp();
    
    //show the results
    showResultsLoading();
          
    //build the url      
     var urlString = neighborhoodURL + name;
     
    //find by neighborhood name
    makeCall("GET",urlString, name, "name");
    
}
//=================================================
//Search for a Neighborhood by X-Y
//=================================================
function findNeighborhoodByXYWCF(xcoord,ycoord) 
{  
    // close help dialog if open
    top.portal.hideHelp();
    
    //show the results
    showResultsLoading();
          
    //build the url      
     var urlString = xyURL + xcoord + "/" + ycoord;;
     
    //find by neighborhood x-y
    var name = (xcoord + ", " + ycoord);
    makeCall("GET",urlString, name, "xy");

}

//=================================================
function findNeighborhoodByAddressCandidate(xcoord, ycoord, address) {
    //close help dialog if open
    top.portal.hideHelp();

    //show the results
    showResultsLoading();

    //build the url
    var urlString = xyURL + xcoord + "/" + ycoord;

    //find by neighborhood x-y
    makeCall("GET", urlString, address, "candidate");
}
//=================================================
//Get List of Neighborhoods
//=================================================
function getNeighborhoods()
{

 Ext.Ajax.request({
               url: "handlers/AJAXProxyHandler.ashx?cdurl=" + encodeURI(getNbrURL),
                timeout: 120000,
                     
                //display the results on success
                success: function(response) 
                {                                                                                                                      
                    //evaluate the response
                    if (resultsObj == null) 
                    {                            
                         resultsObj = Ext.util.JSON.decode(response.responseText);
                         
                         //grab the selectbox for the Neighborhoods
                         var selectbox = parent.document.getElementById("UcSearchNeighborhood1_ddlNeighborhoods");                          
                                                  
                        //dynamically add options to the dropdown
                        for (var indx = 0; indx < resultsObj.Items.length; indx++)
                        {
                          var optn = document.createElement("OPTION");
                            optn.text = resultsObj.Items[indx].Fields[0].Value;
                            optn.value =  resultsObj.Items[indx].Fields[0].Value;
                            selectbox.options.add(optn);
                        }
                    
                    }                            
                 },                            
            failure: function(response) 
	            { 		          
                    //TODO
	            }, 
            form: 'ResultsForm',
            method: 'GET'
            
        });     
}

//=================================================
//Display address candidates
//=================================================
function showCandidatesDialog(candidates) {
    //parent.createCandidateDialog();
    //parent.showCandidateDialog(candidates);
    top.portal.showCandidatesDialog(candidates);
}


//=================================================
//Print a specific layer's records
//=================================================
function printLayer(parentNodeId, nodeId, count, header) {
    //Get the nodes & records information
    var parentNode = root.findChild('id', parentNodeId);
    var layerNode = parentNode.findChild('id', nodeId);
    var records = layerNode.childNodes[(count + 1)].attributes.printInfo;
    
    //Format records
    var recordHtml = "<table border='0' cellspacing='2' cellpadding='2' style='text-align:center;width:99%;'><tr><td>";
    for (var ii=0; ii<records.length; ii++) {
        //recordHtml += "<table cellspacing='1' cellpadding='1' style='background-color:#666;width:100%;'>";
        recordHtml += "<table cellspacing='1' cellpadding='1' style='background-color:#666;width:100%;border-width: 0px; border-spacing: 0px; border-style: none; border-collapse: collapse'>";
        for (var recIndex=0; recIndex<records[ii].Fields.length;recIndex++) {
            var fieldName = records[ii].Fields[recIndex].Name;
            var fieldValue = records[ii].Fields[recIndex].Value;
            
            //Add if it's not OBJECTID
            if (fieldName != "OBJECTID") {
                recordHtml += "<tr><td style='font-weight:bold;background-color:#999;color:#fff;border-width:thin;border-color:black;border-style:solid' width='30%'>" + fieldName;
                recordHtml += "</td><td style='background-color:#fff;color:#333;border-width: thin;border-color:black;border-style:solid'>" + fieldValue + '&nbsp;</td></tr>';
            }
        }
        recordHtml += '</table>';
    }
    recordHtml += '</td></tr></table>';
    
    //Create pop-up and launch print dialog
    //var html = '<html><head><title>' + layerNode.text + ' Results</title></head><body><p style="text-align:center;font-weight:bold;">' + header + '</p>' + recordHtml + '</body></html>';
    var html = '<p style="text-align:center;font-weight:bold;">' + header + '</p>' + recordHtml;
    top.portal.showLayerResultsDialog(html);
//    var printWindow = window.open('','');
//    printWindow.document.write(html);
//    printWindow.document.close();
//    printWindow.print();
}

//=================================================
//Reruns a layer query with a new radius
//=================================================
function ChangeRadius(ddlName, parentNodeId, nodeId) {
    //Get selected value
    var ddl = document.getElementById(ddlName);
    var radius = ddl.options[ddl.selectedIndex].value;
    
    //Get the node
    var parentNode = root.findChild('id', parentNodeId);
    var layerNode = parentNode.findChild('id', nodeId);
    
    //Determine url to call
    if (m_searchType != "address" && m_searchType != "candidate") return
    var url = layerDetailsURL + layerNode.text + "/" + m_searchValue + "/" + resultsObj.Xcoord + "/" + resultsObj.Ycoord + "/" + radius;
    
    //Make call
    callLayerService(layerNode,url);
}

//=================================================
//Calls one of the services to query information
//about a specific layer and displays that
//information in the tree panel.
//=================================================
function callLayerService(node, url) {
    //use ajax to get the layer details
    Ext.Ajax.request({
        url: "handlers/AJAXProxyHandler.ashx?cdurl=" + encodeURI(url),
        timeout: 120000,
                
        //display the results on success
        success: function(response) 
        {                      
            //build the details json object
            var detailsObj = Ext.util.JSON.decode(response.responseText);
                                  
            //remove the first node - loading graphic
            //node.removeChild(node.item(0));
            for (var ii=(node.childNodes.length-1);ii>=0;ii--){
                node.removeChild(node.childNodes[ii]);
            }
            resultsTree.syncSize();

            var ddlName = ""; //stores name of the radius drop-down list
                          
            if (detailsObj.Records.length > 0)
            {
                //add the records to the node
                //appendLayerDetails(detailsObj);    
                    
                var showOnMap = detailsObj.DisplayType;
                var showDisclaimer = detailsObj.Disclaimer;
                var disclaimertext = detailsObj.DisclaimerText;
                var route = detailsObj.Route;
                var routeField = detailsObj.RouteField;
                    
                var html = "<div style='padding-left:80px;'><table border='0' cellspacing='0' cellpadding='2' style='background-color:#fff;width:99%;'><tr><td>";
                
                //records
                for (var i=0; i<detailsObj.Records.length; i++)
                {                           
                    html += "<p><table cellspacing='1' cellpadding='1' style='background-color:#666;width:80%;'>";
                    //Add route portion if necessary
                    if (route && (m_searchType == "address" || m_searchType == "candidate")) {
                        //Make sure the route field is included in the list of fields
                        for (var index=0; index < detailsObj.Records[i].Fields.length;index++) {
                            if (detailsObj.Records[i].Fields[index].Name.toLowerCase() == routeField.toLowerCase()) {
                                html += "<tr><td colspan=\"2\" style=\"background-color:#fff;\"><a href=\"javascript:route('" + m_searchValue + "','" + detailsObj.Records[i].Fields[index].Value + "');\"><img src=\"images/buttons/getdirections_text.gif\" alt=\"get directions\" border=\"0\"></a></td></tr>";
                                break;
                            }
                        }
                    }
                    for (var recIndex=0; recIndex<detailsObj.Records[i].Fields.length;recIndex++)
                    { 
                        var fieldName = detailsObj.Records[i].Fields[recIndex].Name;
                        var fieldValue = detailsObj.Records[i].Fields[recIndex].Value
                        
                        //display a link if it is the object id
                        if (fieldName == "OBJECTID")
                        {
                            if (showOnMap != "RESULTS") 
                            {
                                html += "<tr><td colspan=\"2\" style=\"background-color:#fff;\"><a href=\"javascript:top.zoomToFeature('" + detailsObj.DisplayName + "'," + fieldValue + ");\"><img src=\"images/buttons/showonmap_text.gif\" alt=\"show on map\" border=\"0\"></a></td></tr>";                                                                                             
                            }
                        } else {
                            html += "<tr><td style=\"font-weight:bold;background-color:#999;color:#fff;\" width=\"30%\">" + fieldName + "</td><td style=\"background-color:#fff;color:#333;\">" + fieldValue + "&nbsp;</td></tr>";
                        }
                    } 
                    html +="</table>";
                      
                    //if the record has links                                              
                    if (detailsObj.Records[i].LinkedInfo.length > 0)
                    {
                        var links = "";
                        html += "<br/><span class=\"boldtext\"><b>Related Information</b><br/>";
                        //if there are no records but there is some linked info
                        for (var linkIndex=0; linkIndex < detailsObj.Records[i].LinkedInfo.length ; linkIndex++)
                        {                                                                  
                            //add the links to the table
                            html += "<a href=\"" + detailsObj.Records[i].LinkedInfo[linkIndex].Value + "\" class=\"zoomlink\" style=\"color:#660000;\" target=\"_blank\"><img border=\"0\" src=\"images/linktype/" + detailsObj.Records[i].LinkedInfo[linkIndex].DisplayType + ".gif\">&nbsp;";
                            html += detailsObj.Records[i].LinkedInfo[linkIndex].DisplayName + "</a><br/>"                                                            
                        }                                      
                    }
                    html += "</p>";
                }
                    
                //close the table                          
                html +="</td></tr></table>"; 
                html += "</div>";    
                
                
                //Add drop-down if relevant
                var ddlNameIndex = -1;
                if (detailsObj.Radius > -1) {
                    //Need to add a drop-down
                    ddlName = "ddl" + node.id.replace(/ /,"") + "Radius";
                    var ddlHtml = "<span>Search distance: <select name='" + ddlName + "' id='" + ddlName + "' onChange='ChangeRadius(\"" + ddlName + "\",\"" + node.parentNode.id + "\",\"" + node.id + "\");'>";
                    for (var ii=0;ii<m_distancesInFeet.length;ii++) {
                        ddlHtml += "<option value='" + m_distancesInFeet[ii] + "'>" + m_distancesInText[ii] + "</option>";
                    }
                    ddlHtml += "</select></span>";
                    var ddlNode = new Ext.tree.TreeNode({
                        draggable: false,
                        expanded: true,
                        records:ddlHtml,
                        uiProvider:Ext.tree.customRecordNode,
                        leaf: true,
                        id:node.text+'ddl'
                    });
                    node.appendChild(ddlNode);
                    
                    //Determine index of the option to select
                    for (var ii=0;ii<m_distancesInFeet.length;ii++) {
                        if (m_distancesInFeet[ii] == detailsObj.Radius) {
                            ddlNameIndex = ii;
                            break;
                        }
                    }
                }

                //Determine to display whether the information was found from address search or neighborhood search
                var printTitle = "";
                var disclaim = "";
                if (m_searchType == "address" || m_searchType == "candidate")
                {
                    disclaim += detailsObj.DisplayName + " Information for " + m_searchValue + "</span><br/>";
                    printTitle = detailsObj.DisplayName + " Information for " + m_searchValue;
                }else{
                    disclaim += detailsObj.DisplayName + " Information for " + m_neighborhood + "</span><br/>";
                    printTitle = detailsObj.DisplayName + " Information for " + m_neighborhood;
                }

                //Add print info
                var printHtml = "<a href='javascript:printLayer(\"" + node.parentNode.id + "\",\"" + node.id + "\"," + node.childNodes.length + ",\"" + printTitle + "\");' class='zoomlink'><img src='images/buttons/printer.png' alt='print information' border='0'/> Print this information</a><br/>";
                var printNode = new Ext.tree.TreeNode({
                    draggable: false,
                    expanded: true,
                    records: printHtml,
                    uiProvider:Ext.tree.customRecordNode,
                    leaf: true,
                    id:node.text+'print'
                });
                node.appendChild(printNode);
                
                //Add disclaimer                    
                if (showDisclaimer == "PASSIVE")                        
                {        
                    disclaimertext = escape(disclaimertext);
                     
                    //alert(disclaimertext);
                    disclaim += "<a href=\"javascript:top.portal.showPassiveDisclaimerDialog('" + disclaimertext + "');\" class=\"zoomlink\" style=\"color:#660000;padding-left:80px;\">View Data Source Information</a><br/>";
                        
                }
                                        
                //add the records to the node
                var recNode = new Ext.tree.TreeNode({
                    text: disclaim,
                    draggable:false,
                    expanded:true,                                          
                    records:html,
                    printInfo:detailsObj.Records,
                    leaf:true,
                    uiProvider:Ext.tree.customRecordNode,                                                                        
                    id:node.text+recIndex
                });                        
                node.appendChild(recNode);
            }
               
                                   
            //---------------------------------------
            //For General Links
            //---------------------------------------
            if (detailsObj.LinkedInfo.length > 0)
            {                            
                var links = "<div style='padding-left:80px;'><table border='0' cellspacing='0' cellpadding='2' style='background-color:#fff;width:98%;'>";       
                links += "<tr><td class=\"boldtext\"><b>Related Links</b><br/>";
                //if there are no records but there is some linked info
                for (var linkIndex=0; linkIndex<detailsObj.LinkedInfo.length; linkIndex++)
                {   
                    //add the links to the table
                    links += "<a href=\"" + detailsObj.LinkedInfo[linkIndex].Value + "\" class=\"zoomlink\" style=\"color:#660000;\" target=\"_blank\"><img border=\"0\" src=\"images/linktype/" + detailsObj.LinkedInfo[linkIndex].DisplayType + ".gif\">&nbsp;";
                    links += detailsObj.LinkedInfo[linkIndex].DisplayName + "</a><br/>"                                                                                                                                                
                }
                //close the table                          
                links +="</td></tr></table></div>";
                  
                //add the links to the node
                var linksNode = new Ext.tree.TreeNode({
                    text: "Additional Resources for " + detailsObj.DisplayName,                                       
                    draggable:false,                                        
                    expanded:true,                                         
                    records:links,
                    leaf:true,
                    uiProvider:Ext.tree.customRecordNode,                                                                        
                    id:node.text+'links'
                });                        
                node.appendChild(linksNode);                          
            }
                    
            //------------------------------------------------------------------------
            //If there are no records
            //------------------------------------------------------------------------
            if (detailsObj.Records.length == 0) {
                if (detailsObj.Radius > -1) {
                    //Need to add a drop-down
                    ddlName = "ddl" + node.id.replace(/ /,"") + "Radius";
                    var ddlHtml = "<span>Search distance: <select name='" + ddlName + "' id='" + ddlName + "' onChange='ChangeRadius(\"" + ddlName + "\",\"" + node.parentNode.id + "\",\"" + node.id + "\");'>";
                    for (var ii=0;ii<m_distancesInFeet.length;ii++) {
                        ddlHtml += "<option value='" + m_distancesInFeet[ii] + "'>" + m_distancesInText[ii] + "</option>";
                    }
                    ddlHtml += "</select></span>";
                    var ddlNode = new Ext.tree.TreeNode({
                        draggable: false,
                        expanded: true,
                        records:ddlHtml,
                        uiProvider:Ext.tree.customRecordNode,
                        leaf: true,
                        id:node.text+'ddl'
                    });
                    node.appendChild(ddlNode);

                    //Determine index of the option to select
                    for (var ii=0;ii<m_distancesInFeet.length;ii++) {
                        if (m_distancesInFeet[ii] == detailsObj.Radius) {
                            ddlNameIndex = ii;
                            break;
                        }
                    }
                }
                
                //no records found
                var blank = ''
                if (detailsObj.SearchMethod == 'PIP') {
                    blank = 'The location does not fall within the subject area';
                } else {
                    if (detailsObj.SearchType == 'NEIGHBORHOOD_XY') {
                        blank = 'No information available within the neighborhood boundary';
                    } else {
                        blank = 'No information available within the search radius';
                    }
                }
                var blankNode = new Ext.tree.TreeNode({
                    draggable:false,
                    expanded:true,                                         
                    text:blank,
                    records:"<br/>",
                    leaf:true,
                    uiProvider:Ext.tree.customRecordNode,
                    id:node.text+"0"
                });                        
                node.appendChild(blankNode);

            }
                                    
            //expand the node  
            node.expand();                                                                                                                        
            resultsTree.syncSize();
            
            //Select the right item in the drop-down list
            if (detailsObj.Radius > -1) {
                if (document.getElementById(ddlName)) {
                    document.getElementById(ddlName).value = detailsObj.Radius;
                } else {
                    //Sometimes it seems like it needs just a bit more time before it can "see" the drop-down
                    setTimeout("if (document.getElementById(" + ddlName + ")) {try{document.getElementById(" + ddlName + ").value = " + detailsObj.Radius + ";}alert('hey');}",2000);
                }
            }
               
            if (showDisclaimer == "ACTIVE")
            { 
                //top.portal.showActiveDisclaimerDialog(disclaimertext);
            }
            
//            //Select the right drop-down
//            if (ddlName != '')
//            {
//                try {
//                    document.getElementById(ddlName).selectedIndex = ddlNameIndex;
//                } catch (err) {}
//            }
        },
             
        failure: function(response)                 
        {
             
            //remove the first node - loading graphic
            node.removeChild(node.item(0)); 
                
            var error = "There was a problem retrieving information for this category. Please try again at a later time.";
            var errorNode = new Ext.tree.TreeNode({
                draggable:false,
                expanded:true,                                         
                text:error,
                records:"<br/>",
                leaf:true,
                uiProvider:Ext.tree.customRecordNode,                                                                                                      
                id:node.text+"0"
            });                        
            node.appendChild(errorNode);      
            node.expand();                                                                                                                        
            resultsTree.syncSize();
        }
    });
}

//==============================================
// Show directions
// Added by Cardwell 1/30/2009
//==============================================
function route(from,to)
{
    top.portal.showRoutingDialog(from,to);
}