var dialogPanel;
var waitPanel;
var searchResultsPanel;
var openSearchForm;

// This function is executed when the composite.jsp page loads up. The purpose
// of this function is to initialize the dialog panel
function SearchToolInit() {
    // Define the actual dialog panel and configure it.
    dialogPanel = new YAHOO.widget.Dialog("searchDialogPanel",
        {
            width: "400px",
            fixedcenter: true,
            constraintoviewport: true,
            visible: false,
            draggable: true,
            zindex: 177
        });
        
    // Render the dialog panel. The toolbar item in the map toolbar is 
    // responsible for displaying the dialog panel.
    dialogPanel.render();

    // Create the results panel with some configuration items.
    searchResultsPanel = new YAHOO.widget.Panel("searchResultsPanel",
        {
            width: "750px",
            constraintoviewport: true,
            close: true,
            visible: false,
            draggable: true,
            iframe: true,
            zindex: 176
        });

    // Render the search results panel. This panel will be shown only when
    // results are returned for a query.
    searchResultsPanel.render();
}

// This is the tool item that controls the keyword search button in the map
// toolbar. The only thing that this item does is display a dialog panel. The
// rest of the activities are handled by the dialog panel.
function SearchTool(id, toolName, isMarker) {
    // Inherits from EsriToolItem.
    this.inheritsFrom(new EsriToolItem(id, toolName, new SearchAction(), isMarker));
}

// This action displays the keyword search dialog when the tool is invoked.
function SearchAction() {
    this.inheritsFrom(new EsriAction());

    this.activate = function (elem, callbackFunction) {        
        activeSortButtonId = null;

        // As part of the map refresh, the tools associated with it are
        // also refreshed. The keyword search tool is the current tool item
        // that is active. As a result of the toolbar refresh, the current
        // tool gets activated again. This in turn causes the dialog panel
        // to show up at the end of the zoom. This can happen for any 
        // command or tool that requires a map refresh. To prevent this from
        // happening, the current tool marker is cleared so as to trick the
        // ESRI JavaScript into not activating the search tool item. 
        GCROUtils.getMap().clearCurrentToolItem();

        // Remove the old results if not already done so.
        var searchResultsPanel = $("searchResultsPanel_c");        
        searchResultsPanel.style.visibility = "hidden";
        
        // If the contents of the search panel have already been created then
        // do not create them any more.
        if (!searchPanelCreated) {
            // The contents of the search panel have to go at this specific
            // point of the DOM tree.
            var searchBoxBody = $$('div#searchDialogPanel .bd');
            
            // Iterate through the list of the search links. The hash containing
            // the list has an 'inheritsFrom' value also (probably a bug in
            // Prototype) that needs to be ignored. All of the following happens
            // only during the first time the search is invoked in the session.
            searchLabels.each(function(pair) {
                if (pair.key !== 'inheritsFrom') {
                    // The search link which when clicked will fetch the form.
                    var searchLink = document.createElement('a');
                    searchLink.setAttribute('id', pair.key);
                    searchLink.setAttribute('href', '#');
                    searchLink.appendChild(document.createTextNode(pair.value));
                    
                    // The div that will contain the form.
                    var div = document.createElement('div');
                    div.setAttribute('id', pair.key + '_div');
                    
                    // A separator.
                    var br = document.createElement('div');
                    br.setAttribute('class', 'searchSeparator');
                    
                    // Put them together in the search panel.
                    searchBoxBody[0].appendChild(searchLink);
                    searchBoxBody[0].appendChild(div);
                    searchBoxBody[0].appendChild(br);
                    
                    // Attach the event handler to each search link.
                    YAHOO.util.Event.addListener(pair.key, 'click', function() {
                        // Highlight the search label and set the background
                        // color of the form so as to make it stand out.
                        $(pair.key).style.fontWeight = "bold";
                        $(pair.key + '_div').style.backgroundColor = "#DBF1FD";
                        
                        // If a search form has already been opened then close
                        // it so as to maximize the space for the one selected.
                        if (openSearchForm !== undefined) {
                            Effect.SlideUp(openSearchForm + "_div");
                            $(openSearchForm).style.fontWeight = "normal";
                        }
                        
                        // See if the form has already been fetched, if so then
                        // use it and avoid fetching it from the server.                       
                        var searchFormHTML = searchFormHTMLs.get(pair.key);
                        if (searchFormHTML == null) {
                            // This is the source that needs to be fetched.
                            var url = EsriUtils.getServerUrl(GCROUtils.getMap().formId);
                            url = url.slice(0, url.indexOf('composite') - 1);
                            url += "/searches/" + pair.key + "SearchBody.html";
                            
                            var handleSuccess = function(o) {
                                if (o.responseText !== undefined) {
                                    // On a successful fetch, the source is plugged
                                    // into the div, store the source for future
                                    // use in this session and mark this search as
                                    // the current open one.
                                    $(pair.key + "_div").innerHTML = o.responseText;
                                    searchFormHTMLs.set(pair.key, o.responseText);
                                    openSearchForm = pair.key;
                                    
                                    // Reattach the event handlers as the handlers get
                                    // detached once the div containing the search
                                    // slides up when Effect.SlideUp is called.
                                    searchers.get(pair.key + 'Search').doAfterInit(); 
                                }
                            };
                            
                            var handleFailure = function(o) {
                                if (o.responseText !== undefined) {
                                    $(pair.key + "_div").innerHTML = o.responseText;
                                }
                            };
                            
                            var callback = {
                                success: handleSuccess,
                                failure: handleFailure
                            };
                            
                            var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
                        } else {
                            // If the source has already been fetched then open
                            // it and mark this search as the current open one.
                            $(pair.key + "_div").innerHTML = searchFormHTML;
                            Effect.SlideDown(pair.key + "_div");
                            openSearchForm = pair.key;
                            
                            // Reattach the event handlers as the handlers get
                            // detached once the div containing the search
                            // slides up when Effect.SlideUp is called.
                            searchers.get(pair.key + 'Search').doAfterInit(); 
                        }                       
                    });
                }
            });
            
            // Mark the fact that the search panel has been created.
            searchPanelCreated = true;
        }
        
        // Reset the open sectors list as this is a new search.
        openSectors = new Array();
        
        // Display the search dialog when the user clicks the search icon. 
        dialogPanel.show();
        
        // Since the div element (of the dialog) is hidden by default, need to
        // unhide it every time the user clicks on the search icon.             
        $("searchDialogPanel").style.display = "block";
    };
    
    this.deactivate = function () {
    };
}
